62 lines
		
	
	
		
			3.1 KiB
		
	
	
	
		
			Markdown
		
	
	
	
	
	
		
		
			
		
	
	
			62 lines
		
	
	
		
			3.1 KiB
		
	
	
	
		
			Markdown
		
	
	
	
	
	
|   | --- | ||
|  | title: Prevent Object Mutation | ||
|  | --- | ||
|  |  | ||
|  | 
 | ||
|  |  Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program  and write your own code  | ||
|  | 
 | ||
|  | ### Problem Explanation:
 | ||
|  | 
 | ||
|  | We need to prevent `MATH_CONSTANTS` value from changing. | ||
|  | 
 | ||
|  | ##  Hint: 1
 | ||
|  | 
 | ||
|  | *   Use Object.freeze(obj) to prevent object from being changed. | ||
|  | 
 | ||
|  | > _try to solve the problem now_
 | ||
|  | 
 | ||
|  | ## Spoiler Alert!
 | ||
|  | 
 | ||
|  |  | ||
|  | 
 | ||
|  | **Solution ahead!** | ||
|  | 
 | ||
|  | ##  Basic Code Solution:
 | ||
|  | ```javascript | ||
|  |     function freezeObj() { | ||
|  |       "use strict"; | ||
|  |       const MATH_CONSTANTS = { | ||
|  |         PI: 3.14 | ||
|  |       }; | ||
|  | 
 | ||
|  |       Object.freeze(MATH_CONSTANTS); | ||
|  |        | ||
|  |       try { | ||
|  |         MATH_CONSTANTS.PI = 99; | ||
|  |       } catch( ex ) { | ||
|  |         console.log(ex); | ||
|  |       } | ||
|  |       return MATH_CONSTANTS.PI; | ||
|  |     } | ||
|  |      | ||
|  |     const PI = freezeObj(); | ||
|  | ``` | ||
|  |  <a href='https://codepen.io/dylantyates/pen/OwVxYB' target='_blank' rel='nofollow'>Run Code</a> | ||
|  | 
 | ||
|  | # Code Explanation:
 | ||
|  | 
 | ||
|  | By using Object.freeze() on `MATH_CONSTANTS` we can avoid manipulating it. | ||
|  | 
 | ||
|  | #### Relevant Links
 | ||
|  | 
 | ||
|  | *   <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze' target='_blank' rel='nofollow'>Object.freeze()</a> | ||
|  | 
 | ||
|  | ##  NOTES FOR CONTRIBUTIONS:
 | ||
|  | 
 | ||
|  | *    **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution. | ||
|  | *   Add an explanation of your solution. | ||
|  | *   Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**.  | ||
|  | *   Please add your username only if you have added any **relevant main contents**. ( **_DO NOT_** _remove any existing usernames_) | ||
|  | 
 | ||
|  | > See  <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.
 |