Monday, March 23, 2020

Understand the let and const internally

In my previous post, i had mentioned how the let and const works in Javascript, Now lets dive a bit dipper to understand why things work that way (Memory).

According to what i read and understood, let me put it in my own words.

It is always advisable to use const or else let if variable value is to be changed.

In memory there is something called the stack and heap. All the primitive types are stored on stack and non-primitives are stored on heap.

Primitive types : String, number, boolean, null, undefined.
Non-primitive types: Object, Arrays, functions

For example:

let a=10;

'a' will be stored on the stack, since it is a primitive. Internally in memory 'a' refers to a address which is storing 10. i.e something like


Identifier
Stack
a
6sdfjk7skd
10

So now if we have something like:
let myVar = a;

in the above case we know value of myVar is also to 10 i.e myVar is also pointing to same memory address as the one 'a' is pointing to.

But, if we next set a=20, then will the value of myVar also change? ... No it will not because internally a new memory address is assigned to 'a', which has a value of 20.

Identifier
Stack
a
jfhsfjdsgkd
20
myVar
6sdfjk7skd
10


Lets understand const incase of primitives, why it throws an error when we do something like:

const a=5;
a=10 // gives an error as we cannot reassign const.

What actually happens internally is the following:
the above 2 lines are added to memory like so, in the second row it gives an error when reassigning the memory address to the new location.
Identifier
Stack
a
jfhsfjdsgkd
10
6sdfjk7skd
20


When using non-primitive types like Array, heap comes into picture
example: 

const myArr = []; // variable stored on stack, but its value is stored on heap.

Identifier
Stack
myArr
jfhsfjdsgkd
7hhhhhhh


Heap
7hhhhhhh
[]


myArr.push(10);
After adding the value of 10 , it is updated on Heap address like so, Stack remains the same.
Heap
7hhhhhhh
[10]


This is the reason why we could add or update even after having const for myArr.

Please let me know your comments , suggestions , corrections if any.

No comments:

Post a Comment