Jasyn Marais

Primitive vs Reference Types

11 February 2023

In JavaScript, variables can hold two types of values: primitive types and reference types.

Primitive Types

Primitive types include numbers, strings, booleans, null, undefined, symbol, and BigInt. They are called "primitive" because they are immutable and have no methods or properties.

When you assign a primitive value to a variable, you are actually storing the value itself. It is stored directly in an area of memory called the stack, where it is accessed from.

For example:

let num = 10;
let str = "hello";
let bool = true;
let nothing = null;
let notDefined = undefined;        

Reference Types

Reference types, on the other hand, are objects, arrays, and functions. They are called "reference" because they are mutable and store a reference to the memory location where the value is stored.

When you assign a reference value to a variable, you are actually storing a pointer to that location. It is stored in an area of memory called the heap, and accessed by reference.

For example:

let obj = { name: "Jasyn", surname: "Marais" };
let arr = [1, 2, 3];
function add(a, b) {
    return a + b;
}              

Since reference types are mutable, modifying a value affects all references to that value.

For example:

let obj1 = { name: "Jasyn" };
let obj2 = obj1;
obj2.name = "James";
console.log(obj1.name); // outputs "James"                    

In this example, changing the name property of obj2 also changes the name property of obj1, because they both reference the same object in memory.

Understanding the difference between primitive and reference types is crucial in writing efficient and bug-free code in JavaScript. When working with primitive types, you are working with values, and when working with reference types, you are working with pointers to values.