🟒 EasyCore JSπŸ“– Theory Question

What is the difference between primitive and reference types?

πŸ’‘

Hint

Primitives copy by value; objects copy by reference (the memory address)

Full Answer

Primitive types (string, number, boolean, null, undefined, symbol, bigint) are stored and copied by value.

Reference types (objects, arrays, functions) are stored as pointers. Variables hold a reference β€” assigning copies the reference, not the object.

// Primitives β€” copy by value
let a = 5;
let b = a;
b = 10;
console.log(a); // 5 β€” completely independent

// Objects β€” copy by reference
let obj1 = { x: 1 };
let obj2 = obj1;    // both point to THE SAME object in memory
obj2.x = 99;
console.log(obj1.x); // 99 β€” obj1 was mutated!

// Reference equality
console.log([] === []);   // false β€” different objects
console.log({} === {});   // false β€” different objects

// Functions receive references
function mutate(arr) { arr.push(1); }
const myArr = [];
mutate(myArr);
console.log(myArr); // [1] β€” original was mutated
πŸ’‘ "Pass by value" in JS β€” always. But for objects, the VALUE being passed is the reference (memory address). So you can mutate the object, but you can't make the caller's variable point to a new object.

More Core JS Questions

🟒 EasyWhat is the difference between var, let, and const?β†’πŸŸ’ EasyExplain closures with a practical example.β†’πŸŸ’ EasyWhat is hoisting in JavaScript?β†’πŸŸ’ EasyExplain the event loop, call stack, and microtask queue.β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint