The difference between primitive and reference type values in JavaScript

In JavaScript, there are two main types of values: primitive and reference. Understanding the difference between these two types is crucial for understanding how JavaScript works and for writing efficient and effective code.

A primitive value is a value that is stored directly in the memory location where a variable is declared. These values include numbers, strings, booleans, and special values like null and undefined. When you assign a primitive value to a variable, JavaScript creates a new copy of that value in memory and assigns it to the variable. This means that changes made to the new variable do not affect the original variable and vice versa. Let’s see an example:

let x = 5;
let y = x;
x = 10;
console.log(y); // Output: 5

In the example above, y is assigned the value of x, which is 5. When we change the value of x to 10, it does not affect the value of y. This is because primitive types are passed by value.

On the other hand, a reference value is a value that is stored in a separate memory location and is accessed through a reference. These values include arrays, objects, and functions. When you assign a reference value to a variable, JavaScript creates a new reference to the value in memory and assigns it to the variable. This means that changes made to the new variable will affect the original variable and vice versa. Let’s see another example:

let a = [1,2,3];
let b = a;
a.push(4);
console.log(b); // Output: [1,2,3,4]

In this example, b is assigned the reference of array a. When we push a new value to a, it also gets reflected in b. This is because reference types are passed by reference.

In conclusion, understanding the difference between primitive and reference types in JavaScript is important for understanding how JavaScript works and for writing efficient and effective code. Primitive values are stored directly in memory and changes made to a variable do not affect the original value, whereas reference values are stored in a separate memory location and changes made to a variable will affect the original value.


Posted

in

by