Coercing an array of length 1 to a number

487 Views Asked by At

I came across this in some obfuscated code:

if (o > 0.5) {

I wrongly assumed that o was a number, leading me on a wild goose chase. Turns out o is an array consisting of one value, a number. Further experimentation shows that coercing an array of length 1 evaluates to the value at index 0. For example:

console.log(
  +[9] === 9 // true
);

Apparently, o > 0.5 was shorthand for o[0] > 0.5.

I never knew this was possible before and I am having trouble finding anything written about it. Can someone explain the ins and outs of array coercion?

1

There are 1 best solutions below

2
Will Jenkins On

Further experimentation shows that coercing an array of length 1 evaluates to the value at index 0

Not quite, coercing an array is equivalent to first calling toString() on the array, which returns the comma-concatenated list of values. If there's only one value then you get the string representation of that value. What happens after that follows the normal coercion rules when dealing with a string and another type.