DOUBT with ES6 const

Tell us what’s happening:
The code works fine, I was able to pass the tests. But the console says -

[TypeError: Cannot assign to read only property ‘PI’ of object ‘#’]

What does this mean?

Your code so far


function freezeObj() {
'use strict';
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();

Your browser information:

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

Challenge: Prevent Object Mutation

Link to the challenge:

It’s the error that is thrown when the code tries to execute the following line:

MATH_CONSTANTS.PI = 99;

Since you added Object.freeze(MATH_CONSTANTS) you can no longer change the value in the MATH_CONSTANTS object. When you attempt to do that an error is thrown and caught in the catch block, which executes any code in that block (in this case, printing the error to the console). You are just seeing the error that it is printing to the console.

2 Likes

Thansks for the prompt response.

so the output is from this line.

1 Like

Yes, try { MATH_CONSTANTS.PI = 99; } block tried to reassign the PI key from the frozen object since it was frozen it throws an error. That error is then passed to catch(error) { console.log(error) } this will log the caught error you can do other logic in that catch block though,

catch(error){
console.log(error)
window.alert("PI is a mathematical constant and never changes");
}

I hope that helps a bit more :slight_smile: