DEV Community

Sujith V S
Sujith V S

Posted on

4 1 1 1 1

Primitives and References in JavaScript.

Primitive
String, boolean, number are primitive type.
Let's take a look at an example of it:

let number = 1;
let num2 = number;
number = 2

console.log(num2);

Output:
1
Enter fullscreen mode Exit fullscreen mode

Here, whenever we are assigning the variable 'number' to the variable 'num2', we are actually copying the value of 'number' to the variable 'num2'. So even if we change the value of variable 'number', it won't affect the value of 'num2'. And this behaviour is called primitive.

Reference
Array and objects are reference type in js.
Let's look at an example.

const person = {
    name: 'Max'
}

const secondPerson = person;
person.name = "Ajith"
console.log(secondPerson)

Output:
{ name: 'Ajith' }
Enter fullscreen mode Exit fullscreen mode

In the above code block, the object 'person' is assigned to the variable 'secondPerson'. And then we change the value of name in object 'person' from 'Max' to 'Ajith'. And then we console the secondPerson, we can see that the value of secondPerson has also changed. It is because, the variable 'secondPerson' actually stores a pointer which points to the memory location of the object 'person'. So whenever we change something in 'person', it will also affect 'secondPerson'.

In order to avoid this behaviour, we can use spread operator to copy the values inside an array or object to a new array or objects which is assigned to a new variable.

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay