7
var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behaviour?

George
  • 6,630
  • 2
  • 29
  • 36
Lava kumar N R
  • 425
  • 6
  • 10

5 Answers5

4

Array is casted to string - then concatenated with integer value which is also casted to string.

hsz
  • 148,279
  • 62
  • 259
  • 315
4

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.

  1. Let lprim be ToPrimitive(lval).
  2. Let rprim be ToPrimitive(rval).

toPrimitive tries to pass hint:number (since invoked during arithmetic evaluation) to OrdinaryToPrimitive

  1. If hint is "string", then
    a. Let methodNames be «"toString", "valueOf"».
  2. 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"

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

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

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • 1
    Except when you don't declare that object first `{} + 1` equals `1` but `var obj = {}; obj + 1` will equal `"[object Object]1"` and `{} + {} + 1` equals `NaN` – George Nov 15 '17 at 11:41
0

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);
DanteTheSmith
  • 2,937
  • 1
  • 16
  • 31
  • Question was purely regarding the behaviour not on pushing the value in the array nor adding it to each element. Thanks for the effort anyway – Lava kumar N R Nov 15 '17 at 15:16
0

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);
Ryan Searle
  • 1,597
  • 1
  • 19
  • 30