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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay