In JavaScript, a variable may store two types of values: primitive and reference.

JavaScript provides six primitive types as undefinednullbooleannumberstring, and symbol , and a reference type object.

The size of a primitive value is fixed, therefore, JavaScript stores the primitive value on the stack.

On the other hand, the size of a reference value is dynamic so JavaScript stores the reference value on the heap.

When you assign a value to a variable, the JavaScript engine will determine whether the value is a primitive or reference value.

If the value is a primitive value, when you access the variable, you manipulate the actual value stored in that variable. In other words, the variable that stores a primitive value is accessed by value.

Unlike a primitive value, when you manipulate an object, you work on the reference of that object, rather than the actual object. It means a variable that stores an object is accessed by reference.

To determine the type of a primitive value you use the typeof operator. For example:

let x = 10;
console.log(typeof(x));// number
Code language: JavaScript (javascript)

And

let str = 'JS';
console.log(typeof(str));// string
Code language: JavaScript (javascript)

To find the type of a reference value, you use the instanceof operator:

let refType = variable instanceof constructor;
Code language: JavaScript (javascript)

For example, the following rgb variable is an instance of the Array object:

let rgb = ['red','green','blue'];
console.log(rgb instanceof Array);// true
Code language: JavaScript (javascript)

Copying primitive values

When you assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.

Let’s take a look at the following example.

First, declare a variable a and initialize its value to 10.

var a = 10;
Code language: JavaScript (javascript)