var array = [1,2,4];
array+1 //gives '1,2,41'.
Can anyone explain this behaviour?
var array = [1,2,4];
array+1 //gives '1,2,41'.
Can anyone explain this behaviour?
Array is casted to string - then concatenated with integer value which is also casted to string.
Can anyone explain this behaviour?
This answer attempts to explain this behavior from the point of view of spec.
As per spec, during the run-time evaluation of +
, both expressions (left and right) are converted to their primitive values.
- Let lprim be ToPrimitive(lval).
- Let rprim be ToPrimitive(rval).
toPrimitive tries to pass hint:number
(since invoked during arithmetic evaluation) to OrdinaryToPrimitive
- If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».- Else,
b. Let methodNames be «"valueOf", "toString"». //this gets invoked
Since one of the values were casted to string via 4a) above, string concatenation takes place.
Hence
[1,2,4] + 1
=> [1,2,4].toString() + "1"
=> "1,2,4" + "1"
=> (finally) "1,2,41"
When you use the +
sign with a declared javascipt object (var array
), even if one of the elements is a number, it doesn't perform an arithmetic addition operation - it concatenates the values as two strings.
In your example, your array [1,2,4]
is being casted into a string with a value of 1,2,4
. So 1,2,4
concatenated with 1
is 1,2,41
What did you expect? [2,3,5]?
You haven't wrote a mutator for array, you added 1 to array (which is an object). Why do you expect for object to be able to add 1 to it?
JS figured out you need a primitive from that object and listed that object into a string. Now it knows how to "add" 2 strings (precisely its concatenate) so it did.
If you expected an entire array to get +1 on all elements. You want:
for (var i=array .length; i--;) {
array [i]++;
}
Or
array = array.map(function(e) {return '#' + e});
Or in ES6 and beyond arrow function with map
array = array.map(i => i + 1);
When the operands of an operator are different types, they will be converted to a common type.
Both an array and a Number can be converted to string, this is called coercion.
If you would like to add 1
to an array, you can do this:
var array = [1,2,4];
array.push(1);