Middle
A string concatenation task in JavaScript: what will be displayed on the screen and why? (example with + operator and strings/numbers)
sobes.tech AI
Answer from AI
In JavaScript, the + operator is used for both addition of numbers and concatenation of strings. If at least one of the operands is a string, the others are converted to strings, and concatenation occurs.
Example:
console.log(1 + 2 + '3'); // '33'
console.log('1' + 2 + 3); // '123'
Explanation:
- In the first case,
1 + 2are added as numbers, resulting in 3, then3 + '3'— the number 3 is converted to a string and concatenated, resulting in'33'. - In the second case,
'1' + 2— string + number, the number is converted to a string, resulting in'12', then'12' + 3— again concatenation, resulting in'123'.
Thus, the order of operations and operand types affect the result.