Javascript tips — Object freeze vs const

Leonardo Bruno Lima
3 min readJul 13, 2018

--

Photo by Aaron Burden on Unsplash

The first thing I would like to make clear is there’s no relation and comparison between them, they are two completely different things.

const

The const keyword applies to bindings and creates an immutable binding. In other words, you cannot assign a new value to the binding.

let person = {
name: "Leonardo"
};
console.log(person); //output { name: 'Leonardo' }

Now add another object and assign to the person object:

let person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
person = animal;console.log(person); //output { species: 'snake' }

Ok, if you change the person object declaration to be a constant the code above won’t work anymore:

const person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
person = animal; // ERROR "person" is read-onlyconsole.log(person);

But you can change its values:

const person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
person.name = "Lima";console.log(person); //output { name: 'Lima' }

Make sense right?

Object.freeze

It works on values and it makes an object immutable, i.e. you cannot change, add or delete its properties, but you can assign another instance.

let person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
Object.freeze(person);person = animal;console.log(person); { species: 'snake' }

As you can see above, even using Object.freeze I could assign animal object to to person. Now, let’s try change some property of the person:

let person = {
name: "Leonardo"
};
let animal = {
species: "snake"
};
Object.freeze(person);person.name = "Lima"; //TypeError: Cannot assign to read only property 'name' of objectconsole.log(person);

As you can see, we cannot change any value of the object once it’s frozen, it’s immutable. The only problem is it isn’t deep freeze.

let person = {
name: "Leonardo",
profession: {
name: "developer"
}
};
Object.freeze(person);person.profession.name = "doctor";console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }

If you want make sure the object is deep frozen you have to create a recursive function to freeze each property which is of type object:

function deepFreeze(object) {
let propNames = Object.getOwnPropertyNames(object);
for (let name of propNames) {
let value = object[name];
object[name] = value && typeof value === "object" ?
deepFreeze(value) : value;
}
return Object.freeze(object);
}
let person = {
name: "Leonardo",
profession: {
name: "developer"
}
};
deepFreeze(person);person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name' of objectconsole.log(person);

That’s all folks,

Thanks for reading!

--

--