Reference

Referential equality is when two or more variables point to the same object in memory.

Essential:

github.com/getify/You-Dont-Know-JS

Description:

In JavaScript, all values that are not primitive (string, number, boolean, bigint, symbol, null, or undefined) are objects. This includes arrays, functions, and regular expressions. You need to be aware of referential equality when comparing objects. In plain words, referential equality determines whether the two provided operands refer to the same reference/object instance. The variables are considered referentially equal when compared because they reference the same object.

Table of Contents

  1. 1. Understanding Referential Equality
  2. 2. Value vs Reference
  3. 3. Documentation
  4. 4. Related notes

1. Understanding Referential Equality

    ▪ Example 1: In the first code snippet below, the operatingSystem constant points to the object with the name and developer properties. The operatingSystem2 constant points to the same object as the operatingSystem constant. It does not point to a copy.

    ▪ Example 2: On the contrary, you may have two objects with the exact same shape, but because they are separate objects in memory, they are not considered referentially equal. Let’s think of identical twins as a good example of this phenomenon: they may have the same DNA, but they are still two separate beings:

Example:

Primitives

If you compare primitive types (null, undefined, string, number, boolean or symbol) using the equality operator ===, the result is what you would expect:

Example:

Objects

However, if you compare objects object, array, function (array and function are a sub-class of object), the result isn’t as intuitive as one might think:

Example:

person1 and person2 are both the same type: object. They have the same properties and values. It would make sense if the equality operator returned true when comparing them. But it doesn’t. This is because when you compare objects, the operator is testing reference equality, not value equality. Testing whether they are the same instance, not whether they are the same value. person1 and person2 may have the same value, but they are 2 different object instances. Thus, when compared using the equality operator, it returns false.


2. Value vs Reference

When assigning or passing variables of a primitive, a copy of the value is created. When assigning or passing variables of an object, a copy of the reference is created.

Let’s see two examples:

Example:


3. Documentation

If you’d want to know more about types, grammar, values, coercion or natives, don’t hesitate to visit the specific “Types & Grammar” chapter from You don’t know JavaScript.


All Notes: