DEV Community

Cover image for Destructuring Tweets - Episode 5 - Comparing Arrays
Kai
Kai

Posted on

Destructuring Tweets - Episode 5 - Comparing Arrays

What's kickin', little chicken? Welcome to my series about destructuring those JavaScript quizzes on Twitter. Enjoy the fifth episode!

Snippet of the Week

This week's snippet is from Javascript Startup:

let arrOne = [8];
let arrTwo = [9];

console.log(arrOne == 8);
console.log(arrTwo == 9);
console.log(arrOne < arrTwo);
Enter fullscreen mode Exit fullscreen mode

They first initialize two arrays and store them in a variable. Both of them only have one single item. The first holds the number 8, the second one number 9.
Three logs conclude the snippet by printing the output of different comparisons.

The Output

Well, intuitively, one would guess that this will put out three times false. You can't just compare an array to a number, can you?
Well, the thing is, the contrary is true. The output is actually true, true, and true.

Analysis

To demystify the snippet, we only need to know how Equal (==) behaves when comparing an Object to a primitive type. Cause an Array, is, indeed, of type Object.

When comparing a number to a string, try to convert the string to a numeric value.
(...)
If one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueOf() and toString() methods.

That means that the Array gets converted to a string and the string then to a number. And if we then know how the toString method of Array works, we finally understand why the snippet logs true.

The Array object overrides the toString method of Object. For Array objects, the toString method joins the array and returns one string containing each array element separated by commas.

Remember, we only have one element. Thus we do not have to deal with any comma concatenation.
Well, it's more or less the same for less than (<).

Snippet Summary

Top comments (0)