Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 11, 2022 06:04 pm GMT

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 = 2console.log(num2);Output:1

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' }

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.


Original Link: https://dev.to/sujithvsuresh/primitives-and-references-in-javascript-1jmb

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To