Mutable & Immutable Objects

Joy Evans
2 min readAug 23, 2021

Hey everyone!

Today we’re going to take a closer look at mutable and immutable objects in the world of JavaScript.

What is a “Mutable” object?

A mutable object is an object that can change after its creation.

You can make a variable name point to a new value, but the previous value is still held in memory. Hence the need for garbage collection.

Sesame Street GIF By Saturday Night Live

What is “Garbage Collection”?

Some languages, such as C, require determining whether the allocated memory can be released manually, but JavaScript is quite different. Javascript uses a form of automatic memory management called “garbage collection”(GC). It determines whether a block of allocated memory is no longer necessary and reclaims it. While this may seem like good news to Javascript users, but how can you truly determine whether or not that block of allocated memory is still necessary: References.

What is an “Immutable” object?

An immutable object is an object that cannot be changed after its creation.

Can you make objects immutable?

Well yeah. Of course, at times, you may not want your code to change, which brings me to the question, “How can I make my code immutable then?” That’s when const and Object.freeze() comes in handy.

Const

Using const prevents you from assigning a new value to variables after it's been declared. Check out the example below:

const person = "Joy";person;
// expected output: "Joy"
let person = "Joyce";
// Throws an error that 'person' has already been declared

As shown above, const prevents reassignment of a variable after it’s been declared but let’s see how it works with objects.

const person = {
name: "Joy"
};
person.name = "Joyce"console.log(person.name);
// expected output: "Joyce"
Chris Pratt “What?” GIF

So using const doesn’t quite work for every situation, but that’s why Object.freeze() exists.

Object.freeze()

Using the object.freeze() method freezes an object so it can’t be changed. More specifically, this method prevents new properties from being added and prevents existing properties from being removed, changed, or rewritten. When using the following syntax, Object.freeze(obj) , the return value should be the object that was passed to the function. Check out the example below:

const person = {
name: "Joy"
};
Object.freeze(person);person.name = "Joyce";console.log(person.name);
// expected output: "Joy"

--

--

Joy Evans

Software Engineer | C# | Angular | Ruby on Rails | Javascript | React