freeCodeCamp Challenge Guide: Prevent Object Mutation

Prevent Object Mutation


Hints

Hint 1

  • Use Object.freeze() to prevent mathematical constants from changing.

Solutions

Solution 1 (Click to Show/Hide)
function freezeObj() {
  const MATH_CONSTANTS = {
    PI: 3.14
  };
  // Only change code below this line
  Object.freeze(MATH_CONSTANTS);
  // Only change code above this line
  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.

Relevant Links

30 Likes