whatstheoutput_

#60: [1,2] == '1,2' vs [1,2] == [1,2]

Topic: arrays · Difficulty: ★★

console.log([1, 2] == '1,2');
console.log([1, 2] == [1, 2]);

Output

true
false

Why

When == compares an object (arrays are objects) against a string, the array is first converted to a primitive, which for arrays means calling toString() — effectively joining its elements with commas. [1, 2].toString() is '1,2', so comparing that to the string '1,2' becomes a plain string comparison that matches, giving true. But comparing two DIFFERENT array objects with == never triggers that string conversion in the same way, because neither side is a string or number to force coercion — instead, == falls back to comparing object references, and [1, 2] and [1, 2] are two distinct array objects in memory, so the comparison is false even though their contents look identical.

More arrays puzzles

Play today's puzzle →