Array and Object references in JavaScript!

Marshall Slemp
2 min readOct 7, 2020

--

Have you ever tried to compare to arrays in JavaScript only to see it return false? Even though they look the “same”!

Comparing Arrays and Objects

Um…What?

Theres actually a pretty “simple” explanation of why these comparisons are false! It turns out the variables, like array1, holds a reference/pointer (memory address) for that array. So what is really being stored in the array1 variable is the physical address, in memory, where that array lives. It’s the same with objects! When you declare a variable and give it the value of an array or an object, what you are actually doing is saying, “I would like this variable to keep a reference to the array( or object) I am about to create”. So, the real value array1 holds might look something like:

array1 = "0x7ffc963400c0"

We don’t need to worry too much about the actual address here but it helped me make sense of it all when I seen that little example.

I think I get it…

So if array1 holds a ref of 0x7ffc963400c0 and array2 holds a ref of 0x8ffc32045c3, when you compare the two arrays, you get false.

0x7ffc963400c0 === 0x8ffc32045c3 //=> false

That makes sense! Now you can start to see when you do something like this:

array2 = array1

Why this happens! You are setting array2 = 0x7ffc963400c0 (array1 memory address). So now, array1 === array2 //=> true because they both reference the same array in memory. So when you make a change to array2, you are changing the array at that memory address which is the same array that array1 references!

Hopefully this will help you as you get more into JavaScript, or and programing language(?). [] === [] // false can trip up programmers of all skill but once you understand what the variables actual value is, you can start to see the bigger picture!

The end!

Note: The memory addresses I used in this blog may or may not look like a real memory address! It’s just a placeholder for a real memory address, what ever that may look like.

--

--

No responses yet