Home >Web Front-end >JS Tutorial >What does ? in js mean?
The question mark (?) operator in JavaScript is a conditional operator used to write conditional statements, which assigns values to variables based on conditions: 1. Syntax: variable = condition ? trueValue : falseValue; 2. Usage: Simplify if-else statements, nested conditions, and implement default values. 3. Notes: right association, condition is Boolean value, object reference.
Question mark (?) operator in JavaScript
Question mark (?) operator is a conditional operator used to write conditional statements in JavaScript. It allows you to assign a value to a variable based on a certain condition.
Syntax:
<code>variable = condition ? trueValue : falseValue;</code>
Where:
Usage:
The question mark operator has the following usage:<code>if (condition) { variable = trueValue; } else { variable = falseValue; } // 等价于: variable = condition ? trueValue : falseValue;</code>
<code>variable = condition ? trueValue : (condition2 ? trueValue2 : falseValue2);</code>
<code>const name = user.name || "Guest"; // 如果 user.name 为 undefined 或 null,则 name 被赋予 "Guest" 值。</code>
Notes:
The above is the detailed content of What does ? in js mean?. For more information, please follow other related articles on the PHP Chinese website!