* [Guide] ES6: Prevent object mutation; fixes and enhancements - Remove phantom image - Remove notes for contributors - Change explanation and hints. - Links to markdown * Changed as requested Changed titles as requested by @randelldawson. Note: I'm just used to [MDN](https://developer.mozilla.org/en-US/docs/MDN/Contribute/Guidelines/Writing_style_guide#Page_titles) and other language styles and though it was clearer. Is it ok now for this guide? * fix: removed repl.it link
1.7 KiB
1.7 KiB
title
title |
---|
Prevent Object Mutation |
Remember to use
Read-Search-Ask
if you get stuck. Try to pair program and write your own code
Problem Explanation:
You need to freeze the MATH_CONSTANTS
object so that no one is able to alter the value of PI
, add, or delete properties .
Hint: 1
- Use
Object.freeze()
to prevent mathematical constants from changing.
try to solve the problem now
Spoiler Alert!
Solution Ahead!
Basic code solution:
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();
Code Explanation:
By using Object.freeze() on MATH_CONSTANTS
we can avoid manipulating it.