Why does the solution throw a TypeError?

Tell us what’s happening:
This passes but why does it throw a TypeError?
[TypeError: Cannot assign to read only property ‘PI’ of object ‘#’]

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();

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36.

Challenge: Prevent Object Mutation

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

Hello, Darrell.

Using the const keyword in JavaScript makes a variable immutable. This means you are not allowed to change an objects identity, once it has been assigned. However, strictly a property inside of an object may be altered, unless you specifically declare otherwise. This is what the lesson is getting you to do. You assigned MATH_CONSTANTS.PI = 3.14, then, in your try block, you try to reassign its value to 99. This is not allowed.

You declared MATH_CONSTANTS of type const (technically const is not a type), but you are performing an operation on it that is not allowed with that type. Ergo, TYPE_ERROR.

Read the docs here: const

1 Like

Oh, Thanks! That makes complete sense. I thought my solution to the problem was wrong but that’s the point of this exercise that PI is now immutable.