I don´t know why is there TYPEerror

Tell us what’s happening:
I don´t get what is type error and my solution is exactly the same with the right answer!!!

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/83.0.4103.106 Safari/537.36.

Challenge: Prevent Object Mutation

Link to the challenge:

Object.freeze it only ignores the re assignment of object property, that’s why you getting type error

Cannot assign to read only property ‘PI’ of object ‘#’

It’ll still work ie. the code will still get submitted even with the type error.
The reason for it is because you can’t do Object.freeze on const (Don’t ask me why. Please respond if you find the reason.) . Found a Medium article regarding similar thing.

const doesn’t stop an object to be reassigned, it is why Object.freeze is being taught here

the error comes from `MATH_CONSTANTS.PI = 99;
it is showing that you can’t do the change and it gives an error

Don’t worry about that Exception!

In my opinion [TypeError: “PI” is read-only] in that case is not an error but the expected output when trying to assign a new value to a “const”. It means simply your code works und therefore has been submitted!

Such and similar Exceptions in Javascript are called “TypeError”!
Try also to execute the code without ‘use strict’ or without "try.{…} catch {…} to see the difference!

1 Like

Thanks you! But can you explain what is “use strict” in JavaScript!?

“use strict” is that so called strict or safe mode in Javascript. It allows you to detect errors and correct them. Such errors that are not allowed could be:

  • Use of undeclared variables.
  • Use of Javascript keywords as variable names
  • Duplicating parameters.
  • Deleting parameters or functions.
  • And others…
    I recommend you the youtube video:
    Strict Mode — “use strict” - Beau teaches JavaScript
    from freeCodeCamp.