Arrays/spread operator/check for equal

Little confused with this experiment:

let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];


Check for equal for two arrays with exact same elements is not a thing I guess?

For objects like an array the equality operator does not check the values inside the array, it just checks whether the variables point to the same array. If you did the following:

let thisArray = [true, true, undefined, false, null];
let thatArray = thisArray;

Then your console.log would return true because both of those variables point to the same array. But when you use the spread operator to create a new array, it is making a new copy of the array and thus thatArray points to a completely different array even though the values in the array are exactly the same.

1 Like

Got it.
What if I have two different arrays and I need some kind of check.
I wanna my code say “yes” in the case when I am comparing:

I need some looping through arrays I guess? Compare elements with same indexes step by step?

Yes, because you aren’t wanting to compe the arrays, the container the things are in, you want to compare the things the containers contain.

Like if you had two identical shopping bags, if they both have nothing in, that doesn’t mean they’re the same bag – [] !== []

Got it. Cool analogy, I am a big fan of this kind of explanations!

The analogy doesn’t hold, unfortunately. They would have to be magic shopping bags that can contain the literal exact same item in both, which just ends up being more confusing. It works for empty shopping bags though

However it was enough for me to grasp the idea. I am aware that ideal analogies are a rare occasion.

1 Like

There are a few ways to do this depending on the values in the arrays. Definitely you could create a function that loops through both arrays comparing the values at each index. For simple arrays you could also convert them to a string using JSON.stringify and compare the string values.

I kinda wanna mark ‘Solution’ on a couple of posts. Is that possible?))