Files

49 lines
803 B
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
title: Prevent Object Mutation
---
# Prevent Object Mutation
2018-10-12 15:37:13 -04:00
---
## Hints
### Hint 1
2018-10-12 15:37:13 -04:00
* _Use `Object.freeze()` to prevent mathematical constants from changing._
2018-10-12 15:37:13 -04:00
---
## Solutions
2018-10-12 15:37:13 -04:00
<details><summary>Solution 1 (Click to Show/Hide)</summary>
2018-10-12 15:37:13 -04:00
```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();
2018-10-12 15:37:13 -04:00
```
#### Code Explanation
2018-10-12 15:37:13 -04:00
* By using Object.freeze() on `MATH_CONSTANTS` we can avoid manipulating it.
2018-10-12 15:37:13 -04:00
#### Relevant Links
- ["Object.freeze()" - *MDN Javascript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
</details>