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.
Add a comment
|
2 Answers
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.