Value vs Reference

What actually gets copied when you assign a variable or pass an argument, and why shared objects cause aliasing bugs.

What is it?

When you write b = a or call f(a), something gets copied. The question is what: the value itself, or a reference to where the value lives?

- Pass-by-value: the function receives its own copy. Changing it inside the function doesn't affect the caller. C, and Java/JavaScript primitives, behave this way. - Pass-by-reference: the function receives the caller's variable itself. Assigning to the parameter changes the caller's variable. C++ int& and C# ref do this. - Pass-by-sharing (also called "pass the reference by value"): the function receives a copy of a reference to the same object. Mutating the object is visible to the caller; re-assigning the parameter is not. Python, JavaScript objects, Java objects and Ruby all work this way.

When two names refer to the same object, they are aliases. Aliasing is the source of a classic bug: you change "your copy" and someone else's data changes too. Fixing it means making a real copy, either shallow (new outer container, same inner objects) or deep (everything copied recursively).

Explain like I'm 10

Passing by value is handing someone a photocopy of your document: they can scribble on it and your original is safe. Pass-by-sharing is handing them your house address: they can walk in and rearrange the furniture, but if they cross out the address and write a different one on their note, your house doesn't move.

Examples

Pass-by-sharing in Python: mutate vs re-assign

def add_item(items):
    items.append("new")      # mutates the shared list

def replace(items):
    items = ["x", "y"]       # re-binds the local name only

cart = ["a"]
add_item(cart)
print(cart)   # ['a', 'new']
replace(cart)
print(cart)   # ['a', 'new']  (unchanged)

Shallow vs deep copy (JavaScript)

const original = { name: "Ana", tags: ["admin"] };

const alias = original;                 // same object
const shallow = { ...original };        // new outer object, same tags array
const deep = structuredClone(original); // fully independent

shallow.name = "Bo";       // original.name still "Ana"
shallow.tags.push("dev");  // original.tags is now ["admin", "dev"]!
deep.tags.push("ops");     // original unaffected

console.log(alias === original);              // true
console.log(shallow.tags === original.tags);  // true

Spread, Object.assign, slice() and Python's list.copy() / copy.copy() are shallow. structuredClone (JS) and copy.deepcopy (Python) copy recursively.

The classic aliasing bug: a list of lists

grid = [[0] * 3] * 3      # three references to ONE inner list
grid[0][0] = 1
print(grid)   # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

grid = [[0] * 3 for _ in range(3)]  # three separate inner lists
grid[0][0] = 1
print(grid)   # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

How it works

A variable holding a primitive (in many languages: numbers, booleans) holds the value directly. A variable holding an object holds a reference: in practice a memory address pointing to the object on the heap.

Assignment and argument passing copy whatever the variable holds. For a primitive that is the value; for an object it is the reference. So after b = a with an object, there is still exactly one object and now two references to it.

In Python everything is an object and every name is a reference. Integers and strings just look like values because they are immutable: you can't change them in place, so sharing them is harmless.

True pass-by-reference is different: the parameter is an alias for the caller's variable, not the object. That's why void swap(int& a, int& b) can swap two caller variables in C++, but no function can do that in Python or JavaScript.

cart = ["a"];  add_item(cart)

  caller frame          add_item frame
  +-------------+       +--------------+
  | cart  ---------+    | items  ----+ |
  +-------------+  |    +------------|-+
                   v                 v
                 +---------------------+
                 | list: ["a", "new"]  |   (one object on the heap)
                 +---------------------+

Why does it exist?

Copying a large object on every assignment or function call would be slow and memory-hungry, so most languages pass objects by sharing a reference. The cost of that efficiency is that sharing is invisible in the syntax: b = a looks the same whether it copies a number or shares a 10-million-element list.

When to use it

Think about value vs reference whenever a function receives a list, dict, array or object and you need to know whether it may change it, when you store objects passed in from outside (a constructor keeping a caller's list), and when you return internal state to callers. Copy at those boundaries if the data must stay independent.

When not to use it

Don't deep-copy defensively everywhere "just in case": it costs time and memory and can break things that should be shared (caches, connections, objects with identity). Prefer immutable data or clear ownership so copies are rarely needed.

Common mistakes

  • Saying Python or JavaScript are 'pass-by-reference'. They pass references by value: mutation is shared, re-assignment is not.

  • Using a shallow copy (spread, slice(), list.copy()) and expecting nested objects to be independent.

  • Building a 2D list with [[0] * n] * m in Python, which creates m references to the same inner list.

  • Using a mutable default argument in Python (def f(items=[])). The default list is created once and shared by every call.

  • Comparing objects with === (JS) or is (Python) when you meant to compare contents.

Practice exercises

  1. Easy:

    Write a Python snippet showing that b = a for a list shares the object, then fix it so that changing b leaves a alone.

  2. Medium:

    Write a function withDiscount(order) in JavaScript that returns a new order with every item's price reduced by 10%, without modifying the original order or its nested items.

  3. Hard:

    Implement your own deepCopy for JSON-like data (objects, arrays, primitives) in either language, then extend it to handle cyclic references without infinite recursion.

Interview questions

What is the difference between pass-by-value and pass-by-reference?

Pass-by-value gives the function its own copy of the argument, so changes inside don't affect the caller. Pass-by-reference gives the function an alias to the caller's variable, so even assigning to the parameter changes the caller's variable.

Is JavaScript pass-by-value or pass-by-reference?

Always pass-by-value, but for objects the value is a reference. This is often called pass-by-sharing: a function can mutate an object you passed, but assigning a new object to the parameter doesn't change the caller's variable.

Why can't you write a `swap(a, b)` function in Python that swaps the caller's variables?

Python passes references to objects, not access to the caller's variables. Re-binding the parameters only changes local names. You swap at the call site instead: a, b = b, a.

What is aliasing?

Two or more names referring to the same object. A change made through one name is visible through all the others, which causes bugs when code assumes it has its own copy.

What is the difference between a shallow and a deep copy?

A shallow copy creates a new outer container but reuses the same nested objects. A deep copy recursively copies everything, so the result shares nothing mutable with the original.

What does `[[0] * 3] * 3` produce in Python, and why is it a trap?

A list containing three references to one inner list. Setting grid[0][0] = 1 changes every row. Use [[0] * 3 for _ in range(3)] to create separate rows.

What is the problem with `def f(items=[])` in Python?

Default values are evaluated once, when the function is defined, so every call without an argument shares and mutates the same list. Use items=None and create a new list inside the function.

How do you deep-copy an object in modern JavaScript?

structuredClone(obj). It handles nested objects, arrays, Maps, Sets, Dates and cycles, but not functions, DOM nodes or class prototypes. JSON.parse(JSON.stringify(obj)) is an older workaround that loses undefined, Dates, Maps and cycles.

Why is sharing immutable objects such as strings safe?

Nobody can change an immutable object in place, so aliases can never observe a surprise change. Any 'modification' creates a new object.

How does Java pass objects to methods?

By value, where the value is a reference to the object. The method can mutate the object, but assigning a new object to the parameter has no effect on the caller.