Home >Web Front-end >JS Tutorial >Why Does Javascript Concatenate Before Adding?
Javascript Parentheses Rule for Concatenation and Addition
When working with numeric and string variables in Javascript, it's important to understand the behavior of the ( ) operator. This operator can lead to unexpected results if not properly handled.
Consider the following code:
i = 1; divID = "question-" + i+1;
What you might expect is for divID to be assigned the value question-2, but instead, you get question-11. This is because the ( ) operator performs concatenation when operating on strings and addition when operating on numbers.
To fix this issue, use parentheses to enforce the order of operations:
var divID = "question-" + (i+1)
In this case, the parentheses around i 1 force the addition operation to be performed first, resulting in the expected question-2.
This behavior is not unique to Javascript and is often referred to as the "operator precedence" rule. It dictates that operators with higher precedence (e.g. multiplication, division) are evaluated before those with lower precedence (e.g. addition, concatenation).
Understanding operator precedence is crucial for writing correct and efficient Javascript code. By using parentheses explicitly, you can control the order of operations and avoid unexpected results.
The above is the detailed content of Why Does Javascript Concatenate Before Adding?. For more information, please follow other related articles on the PHP Chinese website!