Hi, Do you know that Javascript is one of the most popular programming language. In the mean time it is one of the most hated programming language too. Do you know why? Because javascript contains lot of weird stuffs with amazing capability in performing operation. On this line, Today let we explore one of the most missed concept to learn as beginners.
Let we start with an example:
let a = 10;
let b = a;
In the previous code, I just assigned value 10
to a variable a
, and I am reassigning the a
to b
. you may thinking what is the issue in it.? let me give a another code snippet.
here I assigning an obj1
to obj2
. Very similar to previous code. But there is a difference. let we see the difference
let a = 10;
let b = a;
b = 20;
console.log(a) // 10
console.log(b) // 20
In the code, I modified the value of b
as 20
but it doesn't affect the value of the a
. as you see on the console.log of a
gives still 10
but b is 20. you may think it is simple. Yes it is.! but behind this, there lies a concept called mutability .
*Generally Primitives are mutable in JS. *
oh! OK. what is primitives.?
In JS Primitives are numbers, string, boolean. whereas Non Primitives are Array, objects.
Let we see the difference between them:
If we declare a variable with string, number, or boolean it will store its data. whenever we try to modify that data it will not overwrite rather it will create a new copy in different memory address.
but, When a variable is assigned with non-primitives like array or object, that variable holds reference to that non-primitive ,instead of that as value.
If you noticed I changed the obj2 but it is affecting the obj1 as well, the reason is non primitive variable stores address not data.
Hope This is helpful.
Cheers,
Happy Learning.!
Top comments (0)