Primitives vs References in JavaScript: Copying, Comparing and Mutating Values
Why changing a copied object changes the original, what "pass by sharing" means for function arguments, why const objects can still change, comparing objects by identity vs by content, shallow copies with spread, deep copies with structuredClone, and why JSON cloning loses data.
kvi5hnuCode Sprout team member6 min readOn this page
Here's a bug almost every JavaScript developer writes once:
const defaults = { theme: "light", fontSize: 14 };
const userSettings = defaults;
userSettings.theme = "dark";
console.log(defaults.theme); // "dark"! The defaults changed too.
The fix is easy once you understand one rule: a variable holding an object doesn't contain the object; it contains a reference to it. This article builds that mental model and then covers copying, comparing and protecting objects, topics that come up in every code review and many interviews.
Values and references
Article 9 split values into primitives (immutable, compared by value) and objects (mutable, compared by identity). Here's what that means when you assign:

let a = 5;
let b = a; // b gets its own copy of 5
b = 6;
console.log(a, b);
const cart = { items: 1 };
const sameCart = cart; // copies the reference: one object, two names
sameCart.items = 2;
console.log(cart.items, cart === sameCart);
5 6
2 true
There's only one object. Assigning it to another variable creates a second name for it, not a second object. Any change made through one name is visible through the other.
Strictly speaking, JavaScript always copies values. For primitives the value is the data itself; for objects the value is a reference (think of it as the object's address). Arrays, functions, dates, maps and class instances are all objects, so this applies to every one of them.
Function arguments: pass by sharing
The same rule applies when you pass an object to a function. The parameter receives a copy of the reference, so the function can mutate the caller's object, but reassigning the parameter only changes the local name:
function addItem(list) {
list.push("milk"); // mutates the caller's array
}
function replaceList(list) {
list = ["bread"]; // only rebinds the local parameter
}
const shopping = ["eggs"];
addItem(shopping);
replaceList(shopping);
console.log(shopping);
[ 'eggs', 'milk' ]
This is called pass by sharing (or "pass by value, where the value is a reference"). JavaScript doesn't have pass by reference in the C++ sense: no function can make the caller's variable point to a different object.
Functions that mutate their arguments surprise callers. Many teams prefer functions that return new values instead, which is also the style that frameworks such as React rely on to detect changes:
const withItem = (list, item) => [...list, item];
const before = ["eggs"];
const after = withItem(before, "milk");
console.log(before, after, before === after);
[ 'eggs' ] [ 'eggs', 'milk' ] false
ES2023 added non-mutating versions of common array methods for exactly this style: toSorted, toReversed, toSpliced and with (part 7).
const doesn't make objects immutable
const prevents reassigning the variable. It says nothing about the object the variable refers to:
const config = { debug: false };
config.debug = true; // allowed: the object is mutable
console.log(config);
try {
config = { debug: false }; // not allowed: the binding is constant
} catch (err) {
console.log(err.name);
}
{ debug: true }
TypeError
To prevent changes to the object itself, use Object.freeze. It's shallow: nested objects stay mutable unless you freeze them too.
"use strict";
const settings = Object.freeze({ theme: "dark", colors: { accent: "teal" } });
try {
settings.theme = "light";
} catch (err) {
console.log(err.name); // strict mode throws; sloppy mode silently ignores
}
settings.colors.accent = "pink"; // nested object is not frozen
console.log(settings.theme, settings.colors.accent, Object.isFrozen(settings.colors));
TypeError
dark pink false
Comparing objects
=== and == compare objects by identity: are these the same object? Two separate objects with identical contents are not equal:
const p1 = { x: 1, y: 2 };
const p2 = { x: 1, y: 2 };
const p3 = p1;
console.log(p1 === p2, p1 === p3);
console.log([1, 2] === [1, 2], [] == []);
false true
false false
This has practical consequences: array.includes({ x: 1 }) never finds an object you didn't get from the array itself, new Set([{}, {}]) has two members, and a Map keyed by objects needs the very same object to look up a value.
To compare contents, you need to walk the structure. A simple version for arrays of primitives:
function sameArray(a, b) {
return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
}
console.log(sameArray([1, 2, NaN], [1, 2, NaN]), sameArray([1, 2], [2, 1]));
const { isDeepStrictEqual } = require("node:util"); // Node.js only
console.log(isDeepStrictEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }));
true false
true
For nested data, use a tested deep-equality function: Node.js's util.isDeepStrictEqual, test framework matchers like toEqual, or utility libraries such as Lodash's isEqual. Comparing JSON.stringify outputs is a tempting shortcut, but it fails when keys are in a different order and loses undefined, NaN and dates.
Copying objects
Shallow copies
A shallow copy creates a new outer object, but nested objects are still shared:
const original = { name: "Ana", address: { city: "Lisbon" }, tags: ["admin"] };
const shallow = { ...original }; // or Object.assign({}, original)
shallow.name = "Bea"; // top level: independent
shallow.address.city = "Porto"; // nested: shared with the original!
console.log(original.name, original.address.city);
const list = [1, 2, 3];
const listCopy = [...list]; // or list.slice(), Array.from(list)
listCopy.push(4);
console.log(list, listCopy);
Ana Porto
[ 1, 2, 3 ] [ 1, 2, 3, 4 ]
Shallow copies are fast and usually enough, because updates often replace nested values rather than mutating them: { ...user, address: { ...user.address, city: "Porto" } }.
Deep copies with structuredClone
structuredClone(value) creates a deep copy: every nested object and array is copied too. It's built into browsers and Node.js 17 and later, and it handles far more than JSON can:
const profile = {
name: "Ana",
joined: new Date(0),
lastLogin: undefined,
limit: Infinity,
roles: new Set(["admin"]),
};
profile.self = profile; // a circular reference
const deep = structuredClone(profile);
console.log(deep.joined instanceof Date, deep.roles.has("admin"), deep.self === deep);
console.log(deep.limit, "lastLogin" in deep);
const { self, ...withoutCycle } = profile; // JSON can't handle the cycle at all
const viaJson = JSON.parse(JSON.stringify(withoutCycle));
console.log(viaJson);
true true true
Infinity true
{
name: 'Ana',
joined: '1970-01-01T00:00:00.000Z',
limit: null,
roles: {}
}
The JSON round trip turned the date into a string, dropped lastLogin, turned Infinity into null and emptied the set, and it throws a TypeError on circular references.
structuredClone has its own limits:
| Can clone | Can't clone |
|---|---|
| primitives (except symbols), plain objects, arrays | functions (throws DataCloneError) |
Date, RegExp, Map, Set, ArrayBuffer, typed arrays | DOM nodes |
Error objects, Blob, File, ImageData | symbols |
| circular and shared references (preserved) | getters, setters and property attributes (values are copied) |
It also copies class instances as plain objects: the copy loses its prototype and methods.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const copy = structuredClone(new Point(3, 4));
console.log(copy, copy instanceof Point, typeof copy.length);
{ x: 3, y: 4 } false undefined
For class instances, give the class its own clone() method or copy constructor.
Common questions
Is JavaScript pass-by-value or pass-by-reference?
Pass by value, always. For objects, the value passed is a reference, so the function can mutate the shared object but can't make the caller's variable point elsewhere. This is often called "pass by sharing".
Why does modifying an array inside forEach or map affect the original?
The callback receives the elements themselves. For object elements, that's a reference to the same object, so the code below mutates the original objects. Return new objects instead: items.map(item => ({ ...item, done: true })).
items.map(item => { item.done = true; return item; })
Does { ...obj } copy methods and getters?
It copies own enumerable properties. A method stored on the object is copied as a reference to the same function. A getter is called, and its current value is copied as a plain data property. Properties inherited from the prototype aren't copied at all.
Is copying expensive? Should I always deep-copy to be safe?
Deep copies of large structures cost real time and memory. Copy what you change: with immutable-update patterns you copy only the path from the root to the modified value and share everything else. Libraries like Immer automate this.
Summary
- Variables hold values. For objects, the value is a reference, so assignment creates a second name for the same object.
- Functions receive copies of references ("pass by sharing"): they can mutate shared objects but not rebind the caller's variables. Prefer returning new values.
constblocks reassignment, not mutation.Object.freezeis shallow.===compares objects by identity. For content equality use a deep-equality helper, notJSON.stringify.- Spread,
Object.assignandslicemake shallow copies.structuredClonemakes deep copies, preserving dates, maps, sets and cycles, but can't clone functions and drops class prototypes.
Practice Questions
What does this print?
const a = [1];
const b = a;
b.push(2);
console.log(a.length);
Answer
2. a and b refer to the same array.
What does {} === {} evaluate to, and why?
Answer
false. Each {} creates a new, distinct object, and === compares objects by identity.
What is team.lead.name?
const team = { lead: { name: "Ana" } };
const copy = { ...team };
copy.lead.name = "Bea";
Answer
"Bea". The spread makes a shallow copy, so copy.lead and team.lead are the same nested object. Use structuredClone(team) or copy the nested level too: { ...team, lead: { ...team.lead } }.
Name three things a JSON.parse(JSON.stringify(x)) clone gets wrong that structuredClone handles.
Answer
Any three of: dates become strings; undefined properties disappear; Infinity and NaN become null; Map and Set become empty objects; circular references throw a TypeError.
Write a function updateCity(user, city) that returns an updated user without mutating the original, where the city is at user.address.city.
Answer
const updateCity = (user, city) => ({ ...user, address: { ...user.address, city } });
Only the objects on the path to the changed value are copied; everything else is shared.
Previous: The JavaScript Global Object and globalThis: Browsers, Node.js and Workers
Next: JavaScript Type Conversion: String(), Number(), Boolean(), parseInt and Formatting Numbers

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.