These are the two value types in JavaScript.
The size of a primitive value is fixed, therefore, JavaScript stores the primitive value on the stack.
Reference TypesThe size of a reference value is dynamic so JavaScript stores the reference value on the heap.
Primitive Types | Reference Types |
---|---|
Number | Object |
String | Function |
Boolean | Array |
Symbol | |
undefined |
|
null |
At the given example below, x
and y
are primitives.
let x = 10;
let y = x;
x = 20;
This shows that x
and y
are completely two independent variables.
Variable | Value |
---|---|
x |
20 |
y |
10 |
let number = 10;
function increase (number) {
number++
}
increase(number);
console.log(number);
Output: 10
At the given example below, x
is an object with property called value
.
let x = { value: 10 };
let y = x;
x.value = 20;
An object is not stored in x
variable. That object is stored somewhere else in the memory and the address of that memory location is stored inside x
variable.
So then when you copy x
into y
variable, it's the address or the reference that is copied. In other words, both x
and y
are pointing on the same object in memory.
And when you modify that object using either x
or y
it changes the immediately visible to the other variable.
Variable | Value |
---|---|
x |
20 |
y |
20 |
let obj = { value: 10 };
function increase (obj) {
obj.value++
}
increase(obj);
console.log(obj);
Output: 11
Primitives are copied by their value while Reference are copied by their reference.