Beginner LevelJavaScript & TypeScript
What is the difference between primitive values passed by value and objects passed by reference?
❓ Interview Prompt: Explain pass-by-value vs pass-by-reference-copy when passing variables into functions in JavaScript.
In JavaScript, variable assignment and function parameter passing behave differently depending on the data type:
Primitive Types (Passed by Value):
Primitives (numbers, strings, booleans, etc.) are copied directly. Modifying a function parameter does NOT affect the original variable outside.
Object Types (Passed by Reference Copy):
Objects, arrays, and functions store a reference (memory address). When passed to a function, the reference copy is passed:
•
Modifying object properties mutates the original object!
•
Reassigning the parameter variable breaks the reference link without mutating the original object.
Code Implementation Example
javascript
// Primitive pass-by-value
let num = 10;
function doublePrimitive(x) {
x = x * 2;
}
doublePrimitive(num);
console.log(num); // 10 (Unchanged!)
// Object pass-by-reference-copy
let person = { name: 'Alice' };
function updateName(obj) {
obj.name = 'Bob'; // Mutates property on original object!
}
updateName(person);
console.log(person.name); // "Bob" (Mutated!)
function reassignObj(obj) {
obj = { name: 'Charlie' }; // Reassigns local parameter reference!
}
reassignObj(person);
console.log(person.name); // "Bob" (Original reference unaffected by reassignment!)💡Primitive copy vs object reference mutation vs object re-assignment.
🎯 Interview Key Takeaway
Primitives are passed by value (copied). Objects are passed by reference value (mutating properties affects the caller, reassigning parameter does not).
#Memory#Reference Types#Functions#Beginner
Back to all JavaScript & TypeScript Questions→