Skip to main content

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 typeHow it is passed
Primitives (numbers, strings, booleans, null, undefined, symbol, bigint)by value
Objects, arrays, functionsby 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); // 10

Explanation:

  • x is assigned a copy of the value of a.
  • Changing x does not affect a.

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 user stores a reference to the object in memory.
  • obj is assigned a copy of this reference, so both variables point to the same object.
  • Changes made through obj are also visible in user.

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:

  • obj first receives a copy of the reference to user.
  • Then obj is 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 typeHow it is passedDoes a change inside the function affect the original?
Primitives (number, string, boolean, null, undefined, symbol, bigint)By valueNo
Objects, arrays, functionsBy 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.