Welcome to my blog where I write mostly about technical things!

Destructuring Tweets – Episode 5 – Comparing Arrays

Welcome to my series about destructuring those JavaScript quizzes on Social Media. Enjoy the fifth episode!

The Snippet

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

console.log(arrOne == 8);
console.log(arrTwo == 9);
console.log(arrOne < arrTwo);

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, and 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.

The 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 (<). It just compares the computed values from the strings computed from the arrays. So, indeed 8 is less than 9.

Further Reading

Less Than Operator
Equal Operator
Array toString Method