Home >Web Front-end >JS Tutorial >The role of question marks in js
The question mark in JavaScript is used with the ternary conditional operator to select one value from two values based on a condition. The syntax of the ternary condition operator is: condition ? value1 : value2, where condition is a Boolean expression, and value1 and value2 are the two values to be selected.
The role of question mark in JavaScript
In JavaScript, the question mark "?" operator is a ternary conditional operation A part of a symbol that selects one of two values based on a condition.
Syntax
<code class="javascript">condition ? value1 : value2</code>
Where:
condition
is a Boolean expression. value1
is the return value when the condition is true
. value2
is the return value when the condition is false
. Working Principle
The ternary conditional operator works as follows:
condition
). true
, then value1
is returned. false
, then value2
is returned. Examples
Here are some examples of using the ternary conditional operator:
<code class="javascript">// 检查一个数字是否为偶数 let isEven = number % 2 === 0 ? true : false; // 根据年龄确定是否可以喝酒 let canDrink = age >= 21 ? "可以喝酒" : "不可以喝酒"; // 设置默认值 let name = name || "John Doe";</code>
Note
The ternary conditional operator is a short alternative to the if-else statement. However, it has the limitation that it can only return one of two values, whereas an if-else statement can return any number of values.
The above is the detailed content of The role of question marks in js. For more information, please follow other related articles on the PHP Chinese website!