Adding number and array produces weird result in javascript

Viewed 43

When working in the console of developer tools in chrome, I types in,
2 + []
and it produced the unexpected result "2". The same happens with every number. What is happening? Also, when we add some number to a nonempty array, it concatenates the number and the first element of that list, e.g., 2+["abc",6] produces "2abc, 6".
Note: I don't have much experience in js.

2 Answers

This is due to coercion in javascript.

both 2 and [] are tried to get converted to a common type - string.

Now, toString method of array returns "" and toString of Number returns "2" in this case.

Therefore to get the result - "2" after "" and "2" are concatenated.

From What I observe, Javascript does implicit type conversions and if both sides of the operand are different, JS will try to typecast them to string in case of + operation.

For example, if you try [12,34].toString() it will return "12,34" and and if you do 2+[] js will interpret it as 2.toString() + [].toString() thus the output "2".

You can try different combinations in your browser console for more experiments.

Related