Multiplying an array with a single value by a number?
javascript
Solution
[3] * 3;
The following steps are taken:
- array is converted to a string `[3] => "3"`
- the string is converted to a number `Number("3") => 3`
- `3 * 3` gives `9`
Similarly, for `[1, 2] * 2`:
- array is converted to a string `[1, 2] => ""1,2"`
- the string is converted to a number `Number("1,2") => NaN`
- `NaN * 3` gives `NaN`
For ECMA freaks among us ;) start here and follow the path `multiplicative operator => ToNumber => ToPrimitive => [[DefaultValue]](number) => valueOf => toString`
Problem
Why does JavaScript allow you to multiply arrays with a single numeric value by another numeric value or by another array with a single numeric value?: ``` [3] * 3; // 9 [3] * 2; // 6 [3] * [3]; // 9 [1, 2] * 2 // NaN ``` I would expect `NaN` to be returned every time but as my experiments in Chrome have demonstrated this is not the case. Is this the expected behavior? Does this behavior make sense? If so, why?