Compare Array in Javascript

I saw this piece of code in Javascript and I can’t understand why it’s false if they have exactly the same values ​​in the two variables.
Why isn’t it true instead?

 const a = [1, 2, 3]; 
 const b = [1, 2, 3]; 
 console.log(a === b) // false

Arrays are objects. When using === to compare objects, it will return true if and only if both sides of === are the same object.

Those are two different arrays (objects) that just happen to have identical elements.

This will print true:

const a = [1, 2, 3];
const b = a;
console.log(a === b); // true
3 Likes

1 Like

@camcode, the easiest way to think about it, when you write const a = [1, 2, 3]; what really happens is this: const a = new Array(1, 2, 3), so as new keyword suggests, every time you use literal notation you create something new - not the same.

3 Likes

OP’s question isn’t unique to JavaScript. The comic isn’t even relevant here, since there’s no coercion involved.

Thanks everyone !!! Now I understand that the comparison is on object not on object’s values.
Are there other examples on compare array like that?

Then what would you suggest to be in the shirt instead of “JS”?

It is indeed not unique to JS, but it’s still true/relevant when understanding Javascript.

AFAIK only JS does that, so the JS shirt stays. Maybe PHP? Sorry I don’t really know.

Overall, I agree that it’s relevant when understanding JS. It’s just not the case given the context of the thread.