In JavaScript, data can be passed either by value or reference. The data type passed as a value is called primitive type while the data type passed as a reference can be collectively called Objects.
Primitive values are stored directly in the variable, and when the variable is assigned a new value, the old value is overwritten. Think of the variables as having no relationship to each other.
let x = 5;
let y = x;
x = 10;
console.log(y); // prints 5
When a variable is assigned a non-primitive value, such as an object or array, it is given a reference to that value instead of the value itself. This reference points to the location in memory where the object is stored, and the variable does not contain the object's value directly.
When a variable, let arr = []
, is assigned the object, it receives the address or location of that object in memory, rather than the object itself. This means that the variable holds a reference to the object rather than containing the object's value directly.
Let's clear it out with examples
In the above example, we have two variables a and b that are assigned to the same object, they will be referentially equal.
However, if we create new objects with the same properties, they will not be referentially equal to the first object, even though they have the same content.
Although the previous explanations may have provided a clear understanding, some confusion may still exist. To further clarify, let's consider a final example and examine it in detail.
// Here b is assigned the reference to the object that a holds,
// so, the comparison returns true
let a = {
name: "Michael",
age: 40
}
let b = a
console.log(b === a) // prints true
//Now b holds a reference to a new object and a holds a reference to the first object, so the comparison returns false
b = {
name: "Richard",
age: 45
}
console.log(b === a) // prints false
If you want to check the properties of two distinct objects, then there are tons of ways you can do that. But the easiest method is using the`JSON.stringify
` method.
In summary, primitive equality compares values and referential equality compares references to objects.
Top comments (0)