Value vs. Reference in JavaScript

by Pinta

2 min read

In JavaScript, when you assign a value to a variable, it can either be a primitive value or a reference to an object. Understanding the difference between value and reference types is crucial in JavaScript, as it affects how data is stored, compared, and passed between functions.

This short article will give you a basic understanding of the concept.

Value Types (Primitive Types):

Value types are simple data types that store a single, immutable value. The following are the primary primitive value types in JavaScript:

  • Number: Represents numeric values (e.g., integers and floating-point numbers).
  • String: Represents sequences of characters.
  • Boolean: Represents true or false values.
  • Undefined: Represents the absence of a value.
  • Null: Represents the intentional absence of any object value.
  • Symbol (added in ECMAScript 6): Represents unique and immutable values, often used as object property keys.
  • BigInt (added in ECMAScript 11): Represents arbitrary-precision integers, which can be very large.

When you assign a primitive value to a variable or pass it as an argument to a function, you are working with a copy of that value. Changes to the variable or parameter do not affect the original value.

let num1 = 5;
let num2 = num1; // num2 now contains a copy of the value 5

num1 = 10; // Changing num1 does not affect num2

console.log(num1); // 10
console.log(num2); // 5

Reference Types (Objects):

Reference types, also known as objects, encompass more complex data structures and are stored as references to memory locations. When you assign a reference type to a variable or pass it as an argument to a function, you are working with a reference to the original object in memory. Changes made to the object will affect all references to that object because they all point to the same memory location. Common reference types in JavaScript include:

  • Objects (including arrays and functions)
  • Dates
  • Regular expressions
  • Custom objects

Manipulating objects means you are operating on the same underlying data, which can lead to unexpected behavior if you're not careful.

let obj1 = { name: "Alice" };
let obj2 = obj1; // obj2 now points to the same object as obj1

obj1.name = "Bob"; // Changes the name property of the shared object

console.log(obj1.name); // "Bob" obj2 and obj1 reference the same object
console.log(obj2.name); // "Bob" obj2 and obj1 reference the same object

In summary, mastering the nuances of value and reference types in JavaScript is a vital skill for any developer. It allows you to harness the language's flexibility and optimize your code while avoiding unintended consequences that can arise when manipulating shared data. By understanding these core concepts, you'll be better equipped to write robust and efficient JavaScript applications.