Do you know what will be the output of this code?
JavaScript
console.log(1 + "2" + "2");
Show answer and explanation
The result is "122", but why is that?
The plus operator is defined for numbers and for strings and the expression is evaluated from left to right.
The interesting thing about the algorithm behind it is, that it checks whether a string is present.
If we take a look at how the runtime handles the expression, it will start with the first part as follows:
1 + "2"
And as the right side contains a string, a concatenation will be made, which results in an intermediary result of:
1 + "2" -> "12"
Only after that, the last part is evaluated as follows:
"12" + "2" -> "122"