The Difference Between Values and References in JavaScript

In JavaScript, how variables store data can be a bit tricky. It all boils down to the difference between values and references.

Primitive Data Types (Values):

  • Numbers (10, 3.14)
  • Strings (“hello”, ‘world’)
  • Booleans (true, false)
  • null
  • undefined
  • Symbols (a unique identifier)

These data types hold the actual value themselves. When you assign a primitive value to a variable, a copy of that value is stored in memory. So, if you change the value of one variable, it won’t affect the other.

Reference Data Types (References):

  • Objects ({ name: “Alice”, age: 30 })
  • Arrays ([1, 2, 3])
  • Functions

These data types are more complex and don’t store the actual data itself. Instead, they store a reference, a memory location pointer, to where the data is actually stored. So, when you assign a reference type to a variable, you’re not copying the data, you’re just creating another variable pointing to the same location in memory.

Here’s the key difference:

  • Changing a primitive value in one variable won’t affect the value in another variable because they are separate copies.
  • Modifying a property of an object (reference type) through one variable will affect all other variables referencing the same object because they all point to the same data in memory.

Example:

JavaScript

let num1 = 10;
let num2 = num1; // num2 is assigned a copy of the value 10

num1 = 20;

console.log(num1); // Output: 20
console.log(num2); // Output: 10 (unchanged)


let person1 = { name: "Alice" };
let person2 = person1; // person2 references the same object as person1

person2.name = "Bob";

console.log(person1.name); // Output: "Bob" (also changed)
console.log(person2.name); // Output: "Bob"

Understanding this distinction is crucial for writing robust JavaScript code. It helps you anticipate how changes in one variable might affect others and avoid unexpected behavior.

A simple but good explanation of value and reference types in JS by Dmitri Pavlutin

https://dmitripavlutin.com/value-vs-reference-javascript/


Comments

Leave a comment