Why isn't Object.freeze() working?

I remember from the ‘Prevent Object Mutation’ course that the catch() threw an error if we tried to mutate the object’s key.
But when I try the same example/code in another course, it just doesn’t work. It doesn’t freeze my object and prevent mutation.

function freezeObj() 
{
  const Users = 
  {
    Alan: 
    {
      age: 27,
      online: false
    }
  };

  Object.freeze(Users);

  try
  {
    Users["Alan"]["age"] = 99;
  }
  catch(ex) 
  {
    console.log(ex);
  }
  
  return Users["Alan"];
}

console.log(freezeObj());    //returns { age: 99, online: false }

Object.freeze(Users.Alan) ; use this insted Object.freeze(Users)

then output will be // {age : 27 ,online : false}

The freeze method works shallowly. So Object.freeze(Users); only freezes the first level. So, you cannot change Users - you cannot change the reference to the object “Alan” - you cannot change that property name or the reference to what it points. But within that object (which wasn’t frozen) you can make changes. So,

Users.Alan.age = 100;

is fine.

But these:

Users.Alan = { age: 99 };
Users.Dave = { age: 12 }

those will throw errors because you are messing with the key/values on the lowest levels.

If you want to freeze all properties throughout, then you would either have to work recursively through the object and freeze things, or you’d have to use something else. (I’m sure lodash has something.)

Incidentally, “catch” isn’t throwing the exception, JS is. But since it’s in the “try” block, the “catch” block can catch the thrown error - rather than let it bubble trough the code to the top level where it would crash the program.

Also, I don’t think it throws an error unless you are in strict mode.

I created a pen to mess around with this, if you want.

1 Like