2 arrays of Same value are not equal in JS.

Shubham Tiwari - Aug 12 '22 - - Dev Community

Hello Guys today i am going to discuss a very little thing that you might have not noticed in Javascript.
I will show you that thing using an example.

Example 1 -

let array1= [1,5,9,14,17];
let array2= [1,5,9,14,17];

console.log(array1 == array2);
console.log(array1 === array2);
Enter fullscreen mode Exit fullscreen mode

Can you guess what will be the output?

Output -

false
false
Enter fullscreen mode Exit fullscreen mode
  • It returned false in both comparsion although the values are equals, number of elements are also equal so, why it returned false? because everything in javascript is an object and arrays are also objects therefore instead of comparing the values or number of elements , it checks the reference of those array which is different that's why it returned false in both the cases.

Example 2 -

let array1= [1,5,9,14,17];
let array2= [1,5,9,14,17];
let array3 = array1
console.log(array3 === array1);
console.log(array3 === array2);
Enter fullscreen mode Exit fullscreen mode

Can you guess now what will be the output?

Output -

true
false
Enter fullscreen mode Exit fullscreen mode
  • Well the reason it returned true while comparing array3 with array1 is because we stored the reference of array1 in array3 so, both are pointing to the same reference while array3 and array2 comparison returned false because they have different references.

How you can then compare these arrays?

The answer is simple , use the toString method to convert the array into strings and then compare them

Example 3-

let array1= [1,5,9,14,17];
let array2= [1,5,9,14,17];
console.log(array1.toString() === array2.toString());
Enter fullscreen mode Exit fullscreen mode

Output -

true
Enter fullscreen mode Exit fullscreen mode
  • So, now it is comparing string values which is equal that's why it returned true this time.

It looks quite confusing and i tried my best to explain and if you find any point wrong please correct it in the comment section.

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank youšŸ‘‡šŸ‘‡ ^^
ā˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player