Skip to content
jshacks.dev
Fundamentals

Primitives vs Objects in JavaScript Values and References

Primitives copy by value and objects copy a reference, which is why changing one variable can change another. See assignment, function arguments and equality.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Vite, Node.js and TypeScript logos.

A function receives an array, sorts it, and the caller's array is sorted too. Two components hold what they think are separate settings objects, and editing one changes the other. These are the same behavior, and the rule that explains it takes about a minute: primitives are copied as values, and objects are reached through references. Everything else, from "pass by reference" arguments to why {} === {} is false, follows from that. This post builds the model with runnable examples on Node.js 24, and the seven primitive types it contrasts with are listed in the post on primitives. The deeper type system story lives in the guide to types and coercion.

Start with assignment. A primitive copy is independent from the moment it is made.

JavaScript
let a = 10;
let b = a;
b = 99;

console.log(a, b);

let title = "draft";
let alias = title;
alias = alias.toUpperCase();

console.log(title, alias);
Text
10 99
draft DRAFT

Changing b did not touch a, and uppercasing alias did not touch title. There is nothing to share, because a primitive is nothing but its content.

Objects behave differently, because the variable holds a reference to an object that lives elsewhere.

JavaScript
const original = { name: "Ada", skills: ["math"] };
const alias = original;

alias.name = "Grace";

console.log(original.name);
console.log(alias === original);
Text
Grace
true

There is one object and two names for it. Editing through alias changed what original sees, since both reach the same place. === returns true because it compares identity: are these the same object.

Mutation and reassignment are different things

Most confusion here comes from treating these two as one. Mutation changes the object that a reference points at. Reassignment points a variable at something else and leaves the old object alone.

JavaScript
let settings = { theme: "light" };
const other = settings;

settings.theme = "dark";
console.log(other.theme);

settings = { theme: "high-contrast" };
console.log(other.theme);
console.log(settings.theme);
Text
dark
dark
high-contrast

The first line changed the shared object, so other saw it. The reassignment gave settings a brand new object, and other kept pointing at the old one. If a bug report says "my copy changed", someone mutated. If it says "my copy did not update", someone reassigned.

Function arguments are copies of the value

You will hear that JavaScript passes objects "by reference". It does not. It passes everything by value, and for an object the value being copied is the reference. The distinction explains what a function can and cannot do to its caller.

JavaScript
function rename(user) {
  user.name = "Renamed";
}

function replace(user) {
  user = { name: "Replaced" };
}

const person = { name: "Original" };

rename(person);
console.log(person.name);

replace(person);
console.log(person.name);
Text
Renamed
Renamed

rename mutated the shared object, and the caller saw it. replace rebound its own parameter to a new object, which did nothing to the caller's variable. A true pass-by-reference language would have let replace change person. This is the model behind the advice to treat arguments as read-only unless a function's whole job is to modify them, and to name such functions with a verb that says so.

Sorting shows the same thing on built-ins. sort() mutates and returns the same array.

JavaScript
const scores = [30, 5, 100];
const sorted = scores.sort((x, y) => x - y);

console.log(sorted);
console.log(scores);
console.log(sorted === scores);

const original = [30, 5, 100];
const copy = original.toSorted((x, y) => x - y);

console.log(copy);
console.log(original);
Text
[ 5, 30, 100 ]
[ 5, 30, 100 ]
true
[ 5, 30, 100 ]
[ 30, 5, 100 ]

toSorted() returns a new array and leaves the original alone, and it is available from Node.js 20. Its existence is a direct answer to this model: the old methods mutate, so a non-mutating twin was added.

Equality compares identity for objects

Two objects with identical fields are two objects. Strict equality has no way to know you consider them the same.

JavaScript
const a = { id: 1 };
const b = { id: 1 };
const c = a;

console.log(a === b);
console.log(a === c);
console.log(JSON.stringify(a) === JSON.stringify(b));
Text
false
true
true

The third line compared serialized content, and it is true because both objects stringify to the same text. That trick depends on key order and fails for values JSON cannot represent, so it is a shortcut and not a rule. Comparing structures by content needs a purpose-built function, a library or a serialization you control. The post on equality for objects and arrays covers the options and their limits.

Copying so the copy is independent

To get a second object that you can change freely, copy it. The depth of the copy decides whether nested objects are shared.

JavaScript
const source = { name: "Ada", skills: ["math"] };

const shallow = { ...source };
const deep = structuredClone(source);

shallow.skills.push("logic");

console.log(source.skills);
console.log(deep.skills);
Text
[ 'math', 'logic' ]
[ 'math' ]

Spread made a shallow copy: a new top-level object whose skills still points at the original array, so the push showed through. structuredClone() copied the whole structure. Which one to use depends on how deep your data goes and whether it contains functions, class instances or other values structuredClone() rejects. The trade-offs are in shallow versus deep copies.

Why the model exists

The split is a trade the language made for speed and simplicity. Copying a number is one machine word, so copying on assignment is free. Copying a large object on every assignment and function call would be expensive and would make shared state impossible, so objects are reached through handles. The cost is the confusion in this post, and the benefit is that passing a ten thousand item array to a function costs the same as passing a number.

Other languages make the choice explicit with value types and reference types, or with pointers. JavaScript hides the pointer and tells you nothing, so the discipline has to come from convention: functions that mutate say so in their names, and shared state is kept small and visible.

Constants do not freeze objects

const prevents reassignment of the binding. It says nothing about the object.

JavaScript
const config = { retries: 3 };
config.retries = 5;
console.log(config.retries);

try {
  config = { retries: 1 };
} catch (error) {
  console.log(error.message);
}
Text
5
Assignment to constant variable.

The property changed freely, and the rebinding threw. Object.freeze() makes an object's own properties read-only, one level deep, and is the tool when you want the object itself to stay put.

A bug that looks like a framework problem

The version of this we see most is shared default state. A module exports a default options object, and every caller that merges into it changes it for everyone.

JavaScript
const defaults = { retries: 3, headers: { accept: "json" } };

function makeClient(overrides) {
  const options = Object.assign(defaults, overrides);
  return options;
}

makeClient({ retries: 9 });

console.log(defaults.retries);
console.log(makeClient({}).retries);
Text
9
9

Object.assign(defaults, overrides) writes into its first argument, so defaults itself was edited, and a second client created with no overrides inherited the first one's retries. The fix is to assign into a new object: Object.assign({}, defaults, overrides), or { ...defaults, ...overrides }. If the defaults contain nested objects, like headers above, the spread is still shallow, so a nested edit would leak the same way. Freezing the defaults with Object.freeze() turns that leak into an error in strict mode.

The symptom is always "works in isolation, fails in the full run". A test suite that creates clients in sequence is where it appears first, because each test inherits the last one's edits. The tell is a result that depends on test order.

Where this model needs care

For code that never mutates its inputs, the whole topic mostly disappears, which is why functional styles and state libraries insist on immutable updates. If your code is full of mutation, every function that takes an object is a possible source of action at a distance.

The model also leaks at the edges: class instances with private fields, Map and Set contents, typed array buffers and objects crossing a worker boundary are copied in different ways, and the structured clone algorithm has its own rules. Check the specific type before assuming a copy is deep.

The semantics are defined in the ECMAScript specification under ECMAScript language types, and MDN explains the same distinction on its page about JavaScript data types and data structures.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.