"Prevent Object Mutation

Hi there, I tried all imaginable combinations of the Object.freeze but it still doesn`t work. I suspect it is a syntax problem.

function freezeObj() {
  const MATH_CONSTANTS = {
    PI: 3.14
  };
  // Only change code below this line

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

Hey there! You can paste block of code in your message by following this technique.

thx, I forgot how to quote :slight_smile:

Also It will be great if you can provide the link of the associated challenge.

Just provide the name of the variable you want to freeze inside the Object.freeze() method.
For example.

const myObject = {
   eg : "Example"
}
Object.freeze(myObject);

If I understand correctly that would be PI but it doesn`t work.

@torrinro Compare the example I have given with this

ok, then it should be

Object.freeze(freezeObj);

right?

Still doesn`t work.

freezeObj is the name of the function. What is the name of the Object variable?

I would say MATH_CONSTANTS ???

yep. You are correct. So put this name inside the method Object.freeze()

1 Like

Yes it works. Thank you for you patience.
The problem was that when I tried this before it gave (and still gives) an error message:
" [TypeError: Cannot assign to read only property ‘PI’ of object ‘#’] "
That made me believe it should not work.
Any idea why that error?

You are getting that error because of this code.
Here in the try block we are trying to modify the MATH_CONSTANTS object. But it is illegal and hence it throws an exception which is being printed on the console.

Again, thank you. Now I really understand.

1 Like