Understanding References in JavaScript

Reference vs Primitive

JavaScript developers often get confused when working with objects and arrays, especially when changes in one variable unexpectedly affect another. In this blog, we’ll break down what references are in JavaScript, why they matter, and how to handle them properly.

What is a Reference in JavaScript?

In JavaScript, a reference is a way to access or point to an object (or non-primitive value) in memory, rather than holding the actual value itself.

Primitive vs Reference Types

Type Example Stored How
Primitive Number, String, Boolean, null, undefined, Symbol, BigInt Stores the actual value
Reference Object, Array, Function, Date, Map, Set Stores a reference (pointer) to the value in memory

Example

// Primitive
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 → original value is unchanged

// Reference
let obj1 = { name: "James" };
let obj2 = obj1;   // obj2 references the same object
obj2.name = "Bond";
console.log(obj1.name); // "Spot" → both point to same object

Explanation:

  • For primitives → b gets a copy of the value. Changing b does not affect a.
  • For objects → obj2 stores a reference to the same memory location as obj1. Changing obj2 affects obj1.

Why it matters

  • When you pass objects to a function, it passes the reference, so changes inside the function can affect the original object.
  • Arrays, objects, and functions are reference types, so assignments or mutations affect the original memory unless you explicitly copy them.

Copying a reference vs creating a new object

let arr1 = [1,2,3];
let arr2 = arr1;  // reference copy
arr2.push(4);
console.log(arr1); // [1,2,3,4] → arr1 changed too

let arr3 = [...arr1]; // new copy
arr3.push(5);
console.log(arr1); // [1,2,3,4] → arr1 unchanged

Summary:

  • Reference = points to the memory location of a value (mostly objects).
  • Primitive = holds the actual value directly.
  • Changing a reference affects all variables pointing to it.

Thank You!