JavaScript Interview Question #4

What is the difference between primitive and reference values in JavaScript?

JavaScript Fundamentals, Types, Scope & Functions Junior Beginner

Quick Interview Answer

Primitive values such as strings, numbers, and booleans are copied as values. Objects, arrays, and functions are reference types in practical JavaScript terminology: a variable stores a reference to the object rather than embedding a separate copy of the entire object.

Detailed Explanation

Primitive values such as strings, numbers, and booleans are copied as values. Objects, arrays, and functions are reference types in practical JavaScript terminology: a variable stores a reference to the object rather than embedding a separate copy of the entire object.

When two variables refer to the same object, a mutation made through one reference is visible through the other. Reassigning one variable, however, does not reassign the other variable.

Code Example

let a = 10;
let b = a;
b = 20;

console.log(a); // 10

const user1 = { name: "Ali" };
const user2 = user1;
user2.name = "Ahmed";

console.log(user1.name); // Ahmed