Note: JavaScript Notes a ? b : c

Published 2024-11-30 12:42 Updated 2026-02-26 12:35 268 words 2 min read

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'...

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 a is a truthy value, execute and return the expression b
  • If the expression a is a falsy value, execute and return the expression c

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 : c can be used as a conditional expression to simplify if-else statements.
  • a & b | c can be used as a bitwise operation for multiple assignments.
  • a & b ^ c can 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~