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
The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence.
Definition. An array is an indexed collection of data elements of the same type. 1) Indexed means that the array elements are numbered (starting at 0). 2) The restriction of the same type is an important one, because arrays are stored in consecutive memory cells.
1 (one, also called unit, and unity) is a number and a numerical digit used to represent that number in numerals. It represents a single entity, the unit of counting or measurement.
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
- Let lref be the result of evaluating AdditiveExpression.
- Let lval be GetValue(lref).
- ReturnIfAbrupt(lval).
- Let rref be the result of evaluating MultiplicativeExpression.
- Let rval be GetValue(rref).
- ReturnIfAbrupt(rval).
- Let lnum be ToNumber(lval).
- ReturnIfAbrupt(lnum).
- Let rnum be ToNumber(rval).
- ReturnIfAbrupt(rnum).
- 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:
- Let primValue be ToPrimitive(argument, hint Number).
- Return ToNumber(primValue).
which leads to ToPrimitive, calling toString
on the array, which leads to Array.prototype.toString, which calls .join
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With