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.
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"
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"
Feel free and comment, share and check out some of the resources posted below. Thanks for reading!