What will be the output? (Object References)
This problem demonstrates how object assignment works by reference in JavaScript.
Quick Navigation: Object Assignment by Reference • Primitives vs Objects • Creating Independent Copies
Object Assignment by Reference
In JavaScript, objects are assigned by reference, not by value. This means when you assign an object to a variable, you're creating a reference to the same object in memory.
What Happens
let a = {x: 1, y: 2}; // Create object in memory
let b = a; // b now references the SAME object
b.x = 3; // Modify the object through b
console.log(a); // {x: 3, y: 2} - a is also affected!
console.log(b); // {x: 3, y: 2} - same objectVisual Representation:
Memory:
┌─────────────┐
│ {x: 1, y: 2}│
└─────────────┘
↑ ↑
a b (both reference the same object)Output
console.log(a); // {x: 3, y: 2}
console.log(b); // {x: 3, y: 2}Both a and b show the same object because they reference the same memory location.
Primitives vs Objects
Primitives: Passed by Value
let x = 10;
let y = x; // y gets a COPY of the value
y = 20; // Only y changes
console.log(x); // 10 (unchanged)
console.log(y); // 20Objects: Passed by Reference
let obj1 = {value: 10};
let obj2 = obj1; // obj2 references the SAME object
obj2.value = 20; // Modifies the shared object
console.log(obj1.value); // 20 (changed!)
console.log(obj2.value); // 20JavaScript Primitives
These are copied by value:
numberstringbooleannullundefinedsymbolbigintEverything else (objects, arrays, functions, dates) is passed by reference.
Creating Independent Copies
Shallow Copy Methods
Spread Operator
let a = {x: 1, y: 2};
let b = {...a}; // Creates new object with copied properties
b.x = 3;
console.log(a); // {x: 1, y: 2} - unchanged
console.log(b); // {x: 3, y: 2}Object.assign()
let a = {x: 1, y: 2};
let b = Object.assign({}, a);
b.x = 3;
console.log(a); // {x: 1, y: 2} - unchangedArray.from() or Spread (for arrays)
let arr1 = [1, 2, 3];
let arr2 = [...arr1]; // or Array.from(arr1)
arr2[0] = 10;
console.log(arr1); // [1, 2, 3] - unchangedDeep Copy
For nested objects, shallow copy isn't enough:
let a = {x: 1, nested: {y: 2}};
let b = {...a}; // Shallow copy
b.nested.y = 3; // Still affects a!
console.log(a.nested.y); // 3 (changed!)
// Deep copy needed:
let c = JSON.parse(JSON.stringify(a)); // Deep copy
c.nested.y = 4;
console.log(a.nested.y); // 3 (unchanged)Note: JSON.parse(JSON.stringify()) has limitations (no functions, dates, undefined, etc.). For complex cases, use libraries like Lodash's cloneDeep().