Translated by AI model Qwen/Qwen3-8B.
Source Language: Simplified Chinese, Target Language: english, Translation Time: 2026-05-01 07:38
.AI translation is for reference only. Accuracy is not guaranteed, please refer to the original text.
I often see a ? b : c in JavaScript source code, but I don't quite understand it, so I looked it up specifically.
In JavaScript, ? and : are a pair of operators, known as 'logical non' and 'logical or' (logical or).
a ? b : c is a ternary operator used to simplify if-else statements. Its working principle is:
- If the expression
ais a truthy value, execute and return the expressionb - If the expression
ais a falsy value, execute and return the expressionc
Therefore, the if-else statement equivalent to a ? b : c is:
if ( a ) {
return b;
} else {
return c;
}
Both methods can achieve the same logic, but the first method uses the ternary operator, and the second method uses the if-else statement.
In JavaScript, the ? and : operators are not only used for logical operations but can also be used in other scenarios, such as:
a ? b : ccan be used as a conditional expression to simplify if-else statements.a & b | ccan be used as a bitwise operation for multiple assignments.a & b ^ ccan also be used as a bitwise operation.
In summary, the ? and : operators are a powerful shorthand tool in JavaScript, helping to improve code efficiency and readability.
If you enjoyed this, leave a comment~