Skip to main content

Command Palette

Search for a command to run...

Objects in JS

Published
3 min read

Let’s talk about how objects in js so we have an clear understanding of what are we doing

Stack vs Heap

In JS there are 2 ways of storing the memory, primitive data-types are stored in a stack form. while non-primitive data-types (arrays, objects) are stored in a Heap form.

A stack can be imagined like a stack of plates placed on a table, while a heap is a more complex structure where in data is not limited to the size of the heap

In stack we have a static sized data which cannot grow according to the needs, while heap can grow as it is a dynamic data format.

let a = 10
let b = a
b = 20

// What do you think will happen to a??

When we create an variable b which is an exact copy of the variable a. The “=“ operator creates an copy of the first data that we have, upon changing the value of b we don’t interfear with the a’s data as it is not referencing to a’s data but rather its generating its own copy.

Imagine you have a piece of paper with the number 10 written on it. This is like variable a.

You then make a photocopy of that paper. This photocopy is like variable b.

If you erase the 10 on the photocopy and write 20 instead, does that change the number on the original piece of paper? No! The photocopy is a separate copy.

THE A WILL REMAIN 10 EVEN IF B’s Value changes as its a copy not a reference.


Non-Primitive Datatypes (objects, arrays)

const array = [1, 2, 3];
const array2 = array;
array2[0] = 22;
console.log("array2++++++++++", array2);
console.log("array++++++++++", array);

What do you think will be the output??

When we use a non-primitive data-type we have 2 things

i) We create a heap storage for the data like in array, we have a heap value stored for [1,2,3]. Okay now we also have a reference to the heap location stored in stack… Too complicated right?? no not really

ii) When we assign a non-primitive data type we have an stack storage of the reference to the memory location, where in the data is stored, and when we creat another array array2, there we just pass the same memory location to it

So when we change the value of array2 then we change the data at that same memory location (lets say 1×1) such that anyone who is also referencing to that location will also experience the change in value.

  • const array = [1, 2, 3]; creates an array in memory. array stores a reference to that location.

  • const array2 = array; copies the reference from array to array2. Both variables now point to the same array.

  • array2[0] = 22; modifies the array in memory. Because both array and array2 point to the same memory location, both will reflect the change.

More from this blog

JavaScript fundamentals

8 posts