Junior — Middle
What happens in JavaScript when adding a string and a number and why is this allowed?
sobes.tech AI
Answer from AI
In JavaScript, when adding a string and a number, it is not arithmetic addition but concatenation (joining) of strings. This is because the + operator in JS is overloaded and performs either addition of numbers or concatenation of strings.
When one of the operands is a string, the other is converted to a string, and concatenation occurs. For example:
let result = "5" + 3; // "53"
Here, the number 3 is converted to the string "3", and the result becomes the string "53".
This behavior is permissible and widely used, but it requires attention to avoid unexpected results when mixing types.