Home >Web Front-end >JS Tutorial >Why Does ' ' Concatenate Strings But '-' Subtracts Numbers in JavaScript?
Divergent Behavior of ' ' and '-' Operators with Strings and Numbers in JavaScript
JavaScript exhibits a puzzling behavior when performing mathematical operations between strings and numbers. Specifically, the behavior of the ' ' and '-' operators varies depending on the operand types involved.
Let's delve into two examples to illustrate this observation:
String Concatenation ( ):
console.log("1" + 1);
Output: "11"
Number Subtraction (-):
console.log("1" - 1);
Output: 0
Reasoning:
This behavior stems from the fact that JavaScript adheres to the "loose typing" paradigm, where type coercion is automatically performed to make operations compatible. However, in the case of the '-' operator and strings, type coercion cannot be applied, leading to the observed behavior.
The above is the detailed content of Why Does ' ' Concatenate Strings But '-' Subtracts Numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!