Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
like image 771
ManavM Avatar asked Jun 14 '19 11:06

ManavM


People also ask

How do you find a single number in an array?

The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence.

Can an array be numbers?

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.

What is single number?

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.


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.

like image 119
CertainPerformance Avatar answered Oct 03 '22 21:10

CertainPerformance