JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What are Primitive and Reference variables in JavaScript?

In JavaScript, there are six primitive values: number, string, boolean, bigint, symbol, and undefined. The variable that holds a primitive value is called a primitive variable. The typeof operator is used to identify the type of primitive value stored in a primitive variable.

Note: When you pass a primitive variable or primitive value to the function, it is passed as call by value.

let x = 123;
let y = "JavaScript";
let z = false;
console.log(typeof x); //number
console.log(typeof y); //string
console.log(typeof z); //boolean

The variable that stores the reference type value is called a reference variable. For example, Object, Array, Map, Set, and all the instances of a class you create using the new keyword are all reference variables. You use the instanceof operator to identify the type of reference value.

Note: When you pass a reference variable or reference type value to the function, it is passed as call by reference.

let pdt = {name:'Google Nest'};
let y = [1, 2, 3, 4, 5];
console.log(pdt instanceof Object); //true
console.log(y instanceof Array); //true

How to copy primitive values in JavaScript?

When a variable having a primitive value is assigned to another variable, then the value stored in the variable is copied to the new variable.

Let's understand the copying process with the help of an example:

First of all, let's declare a variable x and initialize it with 50.

let x = 50;

Now, declare another variable y and assign variable x to y. When you do this, JavaScript will copy the value stored in x to y.

let y = x;

When you change the value stored in variable y, it will not change the value stored in variable x.

y = 100;
console.log(x); //50
console.log(y); //100

How to copy reference values in JavaScript?

When a variable having a reference type value is assigned to another variable, then JavaScript copies the memory address of the reference value to the new variable. And in this way, both the original and copied variables point to the same reference value.

Consider the following example for better understanding.

First of all, declare a variable pdt that will hold an object.

let pdt = {
  name: 'Google Nest Mini',
  quantity: 30
};

After that, declare another variable product and assign variable pdt to product.

let product = pdt;

Using the product variable we will change the name property of an object.

product.name = 'Amazon Echo Dot';

Now, you will find that the name property in both the variables pdt and product are updated.

console.log(pdt); //{name:'Amazon Echo Dot', quantity:30}
console.log(product); //{name:'Amazon Echo Dot', quantity:30}

That is why you need different ways to copy reference type values. If you want to learn how to copy objects in JavaScript, visit clone objects in JavaScript.