Why Identical Array cannot be Equal?

Hello!
While I was doing some experiment, I found below…

let allNum = [1,2,3,4,5];
let check = [1,2,3,4,5];

console.log(allNum==check); // false

Why it returns “false”?? Both arrays have exact the same elements and order.
Please explain this for me.
Thank you in advance!! :slight_smile:

Because when you create an array (or any non-primitive data type) you are refering not to the data itself but where in memory it is stored. When you write

let allNum = [1,2,3,4,5];

You are telling JavaScript, "create a literal data structure [1,2,3,4,5] and put it in memory and then put that memory address into the variable called allNum. This is different than

let x = 4;

where the number 4 is being stored in x. With an array or object, you are storing the address because the data is too big to save at that one address location.

So, when you type:

console.log(allNum==check)

you are asking if the address in allNum is the same as the address in check. They are not - you created a whole new memory allocation and address for check. If you change something in allNum, check will be unaffected because it is a different block of memory at a different address.

Contrast that with:

let allNum = [1,2,3,4,5];
let check = allNum;

console.log(allNum==check); // true

Now they point to the same block of memory with the same address. Changing one will change the other.

This is a weird concept. I have the advantage of learning C first where understanding these kind of things is fundamental to the language, but in JS, it’s easy to miss at first.

Is that clear?

4 Likes