Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding an array to number return a string? [duplicate]

var array = [1,2,4];

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

Can anyone explain this behaviour?

like image 317
Lava kumar N R Avatar asked Nov 15 '17 11:11

Lava kumar N R


People also ask

How do you create an array with the same value?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.

How do you turn a string into an array in Javascript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What property of the array can be used when looping?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .

How do you check if an array contains the same value?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise. let's look at the syntax… const allEqual = arr => arr.


3 Answers

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"

like image 196
gurvinder372 Avatar answered Oct 15 '22 18:10

gurvinder372


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

like image 33
hsz Avatar answered Oct 15 '22 19:10

hsz


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

like image 2
Koby Douek Avatar answered Oct 15 '22 20:10

Koby Douek