1
 let arr = [1,2,3];
 let empArr =[];

 for(var i =0; i< arr.length;i++){

  console.log('First',typeof empArr);

  empArr+=arr[i];

  console.log('Second',typeof empArr)
 }

The above code gives this output

    First object
    Second string
    First string
    Second string
    First string
    Second string

Could anyone explain how in first iteration type was Array Object then after that it became string.How Javascript Engine works here?

  • I don't know why it does it but I do know that you can use `empArr.push(arr[i])` to have it stay an array – Sv443 Oct 26 '18 at 09:35
  • 4
    Because you don't use `+=` to push to arrays, that is a string append operation. – Ben Fortune Oct 26 '18 at 09:35
  • 5
    Possible duplicate of [Why is \[1,2\] + \[3,4\] = "1,23,4" in JavaScript?](https://stackoverflow.com/questions/7124884/why-is-1-2-3-4-1-23-4-in-javascript) – Jeto Oct 26 '18 at 09:35
  • @BenFortune I agree we don't use += to push arrays,by mistake i did this and saw this result so wanted to know how JS engine is behaving here. – Xander Cage Oct 26 '18 at 09:41
  • As per the link @Jeto posted, the `+` operator is not defined for arrays, Javascript will convert arrays into strings and concatenate those – gnusey Oct 26 '18 at 09:46

3 Answers3

3

If we run typeof empArr, we will see empArr an object. No matter if we declare it as an array, internally, it is an object. Further, typeof arr[i] shows arr[i] is a number. Therefore, empArr+=arr[i] means we are trying to add an object and a number. Since we are trying to add two different types, it can happen with the help of coercion, implicitly. Coercion means, converting a value of one type to another. JavaScript performs implicit coercion as per the following rules:

operand + operand = result

  1. If at least one operand is an object, it is converted to a primitive value (string, number or boolean);
  2. After conversion, if at least one operand is string type, the second operand is converted to and the concatenation is executed;
  3. In other case both operands converted to numbers and arithmetic addition is executed.

Note that the primitive value of an array or object is a string.

In our case, empArr is of type object and by rule 1, it is coerced as a string. Now by rule 2, the arr[i] which is a number, is coerced to a string as well and get assigned to empArr.

For more details:

JavaScript addition operator in details

JavaScript type coercion

harman052
  • 919
  • 3
  • 9
  • 14
1

It's because of auto type conversion.

The += is a not an array operator, and as the second operand is string - the 1st is converted to string.

Use empArr.push(arr[i])

Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31
1

According to javascript, typeof [] is "object" ,i.e., every array is actually an object.

if you append anything to a string it will become a string "1"+1 will equal "11"

Anurag
  • 13
  • 3