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
- If at least one operand is an object, it is converted to a primitive
value (string, number or boolean);
- After conversion, if at least one operand is string type, the second operand is converted to and the concatenation is executed;
- 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