How to use Object.freeze() in JavaScript?

How to use Object.freeze() in JavaScript?

Objects and arrays in JavaScript are mutable. This means that we can change an object (or an array) whenever we want. But if we don't want that to happen for any reason and want to make the object immutable.


We can do this using the freeze() method.


An object that you freeze with the freeze() method can no longer be changed; freezing an object with freeze prevents adding new properties, removing existing properties, changing the enumerability, configurability, or writability of existing properties, and changing the values of existing properties. Additionally, freezing an object also prevents the prototype from being modified.


I can add an example code regarding the usage of this method;
const obj = {
    name: "Jack"
};

Object.freeze(obj);

obj.name = "Kelly";
// Throws an error in strict mode

console.log(obj.name);
// expected output: "Jack"