Brief Note: Another illustration of JavaScript reference and values using JavaScript arrays.

Objects are stored and copied by reference. By reference, we mean the location of the object in memory. In contrast, JavaScript primitives are stored and copied as values.

This article will try to illustrate the difference by accessing items in an array.

Array of primitives

const names = ["james", "terungwa", "Jennifer"];
names.indexOf("terungwa"); // 1

The code snippet above describes how to get the index number of a primitive in an array. The array method indexOf compares the actual values of the string and returns the index.

Array of Objects

Let us try to repeat what we did above with an array of objects.

const names = [{ name: "james" }, { name: "terungwa" }, { name: "Jennifer" }];
names.indexOf({ name: "james"}); // -1

Notice that we are not successful this time. The output says the object is not in the array. But we can see the item in the array. Why is this? JavaScript does not compare their exact values, it compares their location in memory (reference).

The object that is defined in the indexOf method is in a different location in memory from a similar item in the array. We can prove this further by making some simple adjustments.

const names = [{ name: "james" }, { name: "terungwa" }, { name: "Jennifer" }];
names.indexOf(names[0]); // 0
// names[0] accesses the array item in its location in memory

As we can see, because we are comparing a valid memory location in the array, it returns the correct answer.