Concatenation Versus Summation with the Plus ( ) Operator in JavaScript
A common issue encountered in JavaScript is the unexpected concatenation of variables instead of their intended summation when using the plus ( ) operator. For example, when the following code is executed, assuming i is initialized to 1:
divID = "question-" + i+1;
The result obtained is "question-11" instead of "question-2".
This phenomenon occurs because the plus ( ) operator handles both concatenation and addition. When applied to different types of operands, the operator prioritizes concatenation if one operand is a string. Therefore, the operations are processed left-to-right:
To obtain the desired summation, enclose the numeric expression in parentheses:
var divID = "question-" + (i+1);
This ensures that the addition of i and 1 is performed first, with the result (2) then concatenated with "question-". The outcome is "question-2" as intended.
This behavior is prevalent in various programming languages, not just JavaScript. It is essential to remember that the order in which operations are executed matters, particularly when dealing with multiple types of operands and operators. Using parentheses explicitly controls the order of evaluation, preventing unexpected results.
The above is the detailed content of Why Does JavaScript Concatenate Instead of Adding with the Plus ( ) Operator?. For more information, please follow other related articles on the PHP Chinese website!