Arguments by value
Main idea
When we pass arguments to a function, JavaScript copies them. But how exactly it copies depends on the data type:
| Data type | How it is passed |
|---|---|
Primitives (numbers, strings, booleans, null, undefined, symbol, bigint) | by value |
| Objects, arrays, functions | by reference (more precisely, by a copy of the reference) |
1. Passing by value
Primitives (numbers, strings, booleans, etc.) are copied entirely.
javascript
let a = 10;
function changeValue(x) {
x = 20; // change the copy
}
changeValue(a);
console.log(a); // 10Explanation:
xis assigned a copy of the value ofa.- Changing
xdoes not affecta.
In memory:
javascript
a → 10
x → 10 (copy)2. Passing by reference (actually: by a copy of the reference)
Objects, arrays, and functions are not copied entirely - instead, a reference to their address in memory is passed.
javascript
const user = { name: "Alice" };
function rename(obj) {
obj.name = "Bob";
}
rename(user);
console.log(user.name); // "Bob"Explanation:
- The variable
userstores a reference to the object in memory. objis assigned a copy of this reference, so both variables point to the same object.- Changes made through
objare also visible inuser.
In memory:
javascript
user ─┐
▼
{ name: "Bob" }
▲
obj ──┘3. But if you change the reference itself inside the function, the original stays untouched
javascript
const user = { name: "Alice" };
function reassign(obj) {
obj = { name: "Charlie" }; // new reference
}
reassign(user);
console.log(user.name); // "Alice"Here:
objfirst receives a copy of the reference touser.- Then
objis redirected to a new object, but the original reference (user) remains unchanged.
Example with an array
javascript
const numbers = [1, 2, 3];
function modify(arr) {
arr.push(4); // change the contents
}
modify(numbers);
console.log(numbers); // [1, 2, 3, 4]But if the reference is reassigned:
javascript
function modify(arr) {
arr = [9, 9, 9]; // create a new array
}
modify(numbers);
console.log(numbers); // [1, 2, 3]Quick recap
| Data type | How it is passed | Does a change inside the function affect the original? |
|---|---|---|
Primitives (number, string, boolean, null, undefined, symbol, bigint) | By value | No |
| Objects, arrays, functions | By reference (copy of the reference) | Yes (if the content is changed) |
| Reassigning the variable inside the function | - | No |
A simple analogy
- By value - like handing over a copy of a sheet of paper: if you write something on your copy, the original does not change.
- By reference - like handing over the address of a safe: both people can open the same safe and change what is inside.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.