1

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?

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43

1 Answers1

0

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.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46
  • The code snippet in my question seems to prove this can't be right. It uses the strict equality sign `===` to compare `+[9]` with `9` and evaluates to `true`. This would not be the case if either side were being coerced to a `String`. – GirkovArpa Aug 03 '21 at 17:57
  • @GirkovArpa `+` before a values is a shortcut way to coerce it to a number, so `[9] == "9"` is true and `+[9] == 9` is true – Will Jenkins Aug 04 '21 at 09:26