Understanding JavaScript Object Assignment and Mutation

Elijah Koulaxis

August 26, 2023

JavaScriptPassByReferenceValue

Meet the Crew: Takis and His Neighbour

Imagine we've got two members in our coding crew: Takis and his buddy. These folks have their own profiles – think of it like a social media page for each of them. Let's represent them in javascript objects:

const member1 = {
    name: 'Takis',
    address: {
        street: 'Kifisias',
    }
}

const member2 = { ...member1 };

In the above code snippet, we're using the spread operator to clone member1 into member2. It's like creating a clone of Takis – same attributes, same details. So far, so good, right?

A Twist: Mutation Unleashed

Takis suddenly decides to move to a new place – "Vouliagmenis" street – and even wants to go by the name Mitsos. Let's see how our objects change:

member1.address.street = 'Vouliagmenis';
member1.name = 'Mitsos';

Let's try to console.log our two objects now, and what do we get? Drumroll, please:

{ name: 'Mitsos', address: { street: 'Vouliagmenis' } }
{ name: 'Takis', address: { street: 'Vouliagmenis' } }

What just happened: Pass by Reference

The reason behind this behavior lies in how javascript handles object assignment. When we assigned member1 to member2 using { ...member1 }, we created a new object that copied the structure of member1. It might seem like we've cloned the object entirely, however, the outer structure is duplicated, but the nested parts are shared.

In javascript, objects are passed by reference. This means that when we change the properties of an object, those changes are reflected wherever that object is referenced. Imagine you and your friends are all listening to the same playlist at a party. If one person adds a new song to the playlist or skips a track, everyone at the party hears the same change.

Conclusion: The Power of Fundamentals

Understanding the core of how things work in coding is like having a key to unlock endless possibilities. Remember that diving into the 'why' and 'how' is literally your compass to success. It's not just about building; it's about knowing the mechanics behind it. These fundamentals effectively become your toolkit for innovation and problem-solving.

So, keep your curiosity alive, keep learning, and master the fundamentals!

Tags:
Back to Home