Prevent Object Mutation TypeError

Prevent Object Mutation TypeError
0

Tell us what’s happening:

The code itself is fine, but I get this error despite having overcome the challenge:

TypeError: Cannot assign to read only property 'PI' of object '#<Object>'

3.14

In my code “const PI” works being let or const, no matter which one I use, I overcome the challenge but the error still comes out.

Your code so far


function freezeObj() {
  "use strict";
  const MATH_CONSTANTS = {
    PI: 3.14
  };
  // change code below this line
  Object.freeze(MATH_CONSTANTS);

  // change code above this line
  try {
    MATH_CONSTANTS.PI = 99;
  } catch( ex ) {
    console.log(ex);
  }
  return MATH_CONSTANTS.PI;
}
const PI = freezeObj();
console.log(PI); 

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/prevent-object-mutation

You should see this error. That is what the catch is displaying to the console. This is proving that the Object.freeze method is actually preventing you from changing the value of the PI property of MATH_CONSTANTS.

1 Like