Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 10

Primitive vs. Reference Types: Pass-by-Value vs. Pass-by-Reference

This lesson is built with resources from youtube.com, 33jsconcepts.com and 1 more site.

Hello! In our last lesson, we identified the five most common primitive data types: string, number, boolean, null, and undefined. We saw them as the fundamental building blocks of data in JavaScript.

Today, we'll dive deeper into one of the most important—and often misunderstood—concepts in the language. Our goal is to explain the fundamental difference between primitive types (pass-by-value) and reference types (pass-by-reference).

This isn't just theory; it's a practical concept that explains why some variables seem to change unexpectedly while others don't. Mastering this will prevent countless bugs and is crucial for understanding how data flows through your applications, a skill you'll lean on heavily when working with Next.js and TypeScript.

The "Why": How JavaScript Remembers Data

The difference in behavior between primitive types and more complex types (like objects and arrays, which we call reference types) comes down to how JavaScript stores them in your computer's memory.

Think of your program's memory as having two main areas: the Stack and the Heap. Since you appreciate deep dives and visual aids, let's establish this mental model.

  • The Stack: A highly organized, fast, and size-limited memory space. It's like a stack of boxes, where each box has a label (the variable name) and holds a piece of information. The Stack is used to store primitive values directly.
  • The Heap: A large, less organized, and dynamic memory space. It's like a vast warehouse where larger, more complex items (like objects and arrays) are stored. The Stack doesn't hold these large items directly; instead, it holds a small "address card" or reference that tells it where to find the item in the Heap.

This image provides a great visual for this concept:

Stack and Heap Memory Allocation for Reference Types
This diagram illustrates how variables for reference types (like 'array' and 'obj') are stored on the Stack as references (pointers) that point to the actual data stored in the much larger Heap.

So, the rule is:

  • A variable holding a primitive type has the actual value (e.g., 42, true, "hello") stored directly on the Stack.
  • A variable holding a reference type (like an object or array) has a pointer (memory address) stored on the Stack, which points to the actual object in the Heap.

This fundamental difference in storage is the root cause of all the behaviors we're about to explore.


Seeing the Difference: Copying Variables

The easiest way to see the distinction between primitives and reference types is to see what happens when we copy a variable.

Primitives: Copied by Value

When you assign a variable holding a primitive to a new variable, the value itself is copied. Each variable becomes completely independent.

let myScore = 95;

// The value 95 is COPIED to highScore
let highScore = myScore;

// We change highScore
highScore = 100;

console.log(myScore);   // Output: 95
console.log(highScore); // Output: 100

Changing highScore had no effect on myScore because highScore received its own, separate copy of the value 95. This behavior is called pass-by-value.

Immutability of JavaScript Primitives
As this image shows for strings, primitive values are immutable. Operations don't change the original value; they create and return new ones. When we "copy" a primitive, we are creating a new, independent value.

Reference Types: Copied by Reference

When you assign a variable holding an object or array to a new variable, you are not copying the object. Instead, you are copying the reference (the address card). Both variables now point to the exact same object in the Heap.

const player1 = {
  name: "Mario",
  lives: 3
};

// The REFERENCE to the object is copied, not the object itself
const player2 = player1;

// We change the object using the 'player2' reference
player2.lives = 2;

// Let's check player1...
console.log(player1.lives); // Output: 2  <-- Wait, what?!
console.log(player2.lives); // Output: 2

Because both player1 and player2 hold a key to the same house (the object in the Heap), a change made through one key is visible when you look through the other. This is called pass-by-reference.

This next video does a wonderful job of animating this exact concept of Stack, Heap, and how primitives and objects behave differently when copied.

JavaScript - Reference vs Primitive Values/ Types

The video 'JavaScript - Reference vs Primitive Values/ Types' from Academind provides excellent animations that bring the concepts of Stack, Heap, and copying to life. Pay close attention to the visual distinction between how numbers and objects are handled.

Please watch these two key segments: Copying a Primitive (01:37 - 04:23): See how changing one variable does not affect its copy. Copying a Reference Type (04:23 - 06:46): Observe how changing the copied object does affect the original.


Deeper Dive: Passing Arguments to Functions

This same logic applies when you pass variables into functions, which is where many bugs originate. Passing an argument to a function is essentially the same as assigning it to a new variable.

The following video demonstrates this beautifully, showing live examples in the browser console.

JavaScript Value vs. Reference (Primitives vs. Objects) -- Tutorial for Beginners

The 'JavaScript Value vs. Reference' video from ColorCode provides clear, animated examples of how passing primitives and objects to functions works differently.

Please watch these segments, which cover both passing arguments and variable assignment. Passing a Primitive to a Function (09:59 - 11:11): Notice how the original variable remains unchanged. Passing an Object to a Function (11:11 - 12:53): See how mutating the object inside the function affects the original. Copying a Primitive Variable (13:39 - 14:49): Reinforces the pass-by-value concept. Copying an Object Variable (14:49 - 16:18): Reinforces the pass-by-reference concept.


The Most Accurate Term: Call by Sharing

You have a preference for deep, accurate theory, so it's time to refine our terms. While "pass-by-value" and "pass-by-reference" are very common, the most precise term for how JavaScript handles objects is call by sharing.

This reading provides a fantastic "House Key Analogy" and explains the subtle but crucial difference between mutating an object and reassigning it.

Primitives vs Objects: How JavaScript Values Actually Work

The guide 'Primitives vs Objects' from 33jsconcepts.com offers a technically precise explanation. It will clarify the terminology and introduce you to the 'golden rule' of mutation vs. reassignment.

Please read the following sections. They build on everything we've discussed and give you the most accurate mental model. Start at "How Primitives and Objects Behave". This summarizes the core characteristics. Read "The House Key Analogy". This is a powerful mental model. Continue with "Call by Sharing: How JavaScript Passes Arguments". This is the core of the deep theory, explaining the 'Golden Rule' of mutation versus reassignment. Read "Copying Behavior: The Critical Difference" and "Comparison Behavior". These sections solidify the practical consequences.

The key takeaway from that reading is this "Golden Rule": When you pass an object to a function...

  1. Mutation works: If you change a property of the object (e.g., person.name = 'Bob'), the original object is affected.
  2. Reassignment doesn't: If you try to replace the entire object (e.g., person = { name: 'Charlie' }), this only affects the local variable inside the function. The original variable outside is unchanged because you're just giving the local variable a new address card to a brand new object.
Test your understanding!

Consider the following code snippet. What will be logged to the console at the end? Try to trace the values and references.

function updateInventory(item) {
  item.quantity = 0;
  item = { name: 'Health Potion', quantity: 20 };
}

const sword = {
  name: 'Master Sword',
  quantity: 1
};

updateInventory(sword);

console.log(sword.quantity);
Show answer

The console will log 0.

Here's the step-by-step explanation:

  1. We declare a constant sword and assign it an object. It lives in the Heap.
  2. We call updateInventory(sword). The function parameter item gets a copy of the reference to the sword object. Both sword (outside) and item (inside) point to the same object in memory.
  3. Inside the function, item.quantity = 0; is executed. This is a mutation. It follows the reference and changes the quantity property of the original sword object from 1 to 0.
  4. Next, item = { name: 'Health Potion', quantity: 20 }; is executed. This is a reassignment. A completely new object is created in the Heap, and the local variable item is now made to point to this new object. This does not affect the original sword variable at all.
  5. The function finishes.
  6. console.log(sword.quantity); logs the quantity of the original sword object, which was mutated to 0 in step 3.

Conclusion

You've just tackled one of the most fundamental concepts in JavaScript! Understanding this distinction is a huge step toward writing predictable and bug-free code.

Key Takeaways:

  • JavaScript has two main categories of types: Primitive Types and Reference Types (objects, arrays).
  • Their core difference lies in how they are stored in memory. Primitives are stored directly on the Stack; Reference types are stored on the Heap, with a pointer on the Stack.
  • Primitives are passed by value: When you copy or pass a primitive, you get a new, independent copy of the actual value.
  • Reference Types are passed by reference (or more accurately, by sharing): When you copy or pass an object, you get a copy of the pointer. Both the original and the copy point to the same object in memory.
  • Mutation vs. Reassignment: Modifying an object's properties through any reference will affect the single, shared object. Reassigning a reference variable simply makes it point to a new object, leaving the original object untouched.

In our next lesson, we will continue exploring data types by learning how to check a variable's type using the typeof operator and how JavaScript handles converting values from one type to another.