Why is an array with a single number in it considered a number?

Viewed 754

While working on an isNumeric function I found this edge case:

[5] is considered a number, can be used with numerical operators like +, -,/ etc and gives 5 when given to parseFloat.

Why does JavaScript convert a single value array to a number?

For example

const x = [10];
console.log(x - 5, typeof x);

gives

5 object
1 Answers

The - operator attempts to coerce its surrounding expressions to numbers. [5], when converted to a primitive (joining all elements by ,), evaluates to '5', which can be clearly converted to a number without issue.

See the spec:

AdditiveExpression : AdditiveExpression - MultiplicativeExpression

  1. Let lref be the result of evaluating AdditiveExpression.
  2. Let lval be GetValue(lref).
  3. ReturnIfAbrupt(lval).
  4. Let rref be the result of evaluating MultiplicativeExpression.
  5. Let rval be GetValue(rref).
  6. ReturnIfAbrupt(rval).
  7. Let lnum be ToNumber(lval).
  8. ReturnIfAbrupt(lnum).
  9. Let rnum be ToNumber(rval).
  10. ReturnIfAbrupt(rnum).
  11. Return the result of applying the subtraction operation to lnum and rnum. See the note below 12.7.5.

Where ToNumber does, in the case of an object:

  1. Let primValue be ToPrimitive(argument, hint Number).
  2. Return ToNumber(primValue).

which leads to ToPrimitive, calling toString on the array, which leads to Array.prototype.toString, which calls .join.

Related