Function Parameters

Understanding how data is passed into functions is one of the most important concepts in JavaScript. It determines whether a function changes your original data or just a copy of it.

1. Primitives: Pass by Value

When you pass a primitive type (Number, String, Boolean, null, undefined) to a function, JavaScript creates a copy of that value.

The function gets its own independent version. Changes inside the function never affect the variable outside.

Example

let age = 20;

function changeAge(val) {
  val = 100; // This changes the LOCAL copy 'val'
  console.log(`Inside function: ${val}`); // 100
}

changeAge(age);
console.log(`Outside function: ${age}`); // 20 (Unchanged)

Analogy: It's like emailing a file to a friend. If they edit their copy, your original file on your computer remains unchanged.

2. Objects: Pass by Reference (The Tricky Part)

When you pass an object (Object, Array, Function) to a function, you are actually passing a reference (a memory address). You are not copying the whole object.

Both the outside variable and the function parameter point to the exact same spot in memory.

Case A: Mutating Properties (Side Effect)

If you change a property of the object inside the function, the change is reflected everywhere.

Analogy: Sharing a Google Doc. If someone edits the text, you see the changes immediately because you are both looking at the same document.

This is a common interview "gotcha." If you assign a completely new object to the parameter variable using =, it breaks the link. It does not replace the original object outside.

Why? You only changed what the variable vehicle points to. You didn't touch the memory where "Toyota" lives.

3. How to Pass Objects "Safe by Value" (Immutability)

If you want to pass an object to a function but ensure the original remains untouched, you must manually create a copy before modifying it.

A. Shallow Copy (Spread Operator)

Best for flat objects.

B. Deep Copy (structuredClone)

Necessary if your object contains nested objects (like arrays or other objects inside it).

Summary Table

Data Type

Passing Mechanism

Effect of Change inside Function

Primitive (Number, String...)

By Value (Copy)

None. Original is safe.

Object (Array, Object...)

By Reference

Mutates Original if you change properties (e.g., obj.x = 1).

Object (Reassignment)

Broken Reference

None. obj = {} only changes the local variable.

Last updated