DEV Community

Sujith V S
Sujith V S

Posted on

Primitives and References in JavaScript.

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

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


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.

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

const person = {
    name: 'Max'

const secondPerson = person; = "Ajith"

{ 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)