Conditional operators: if, '?'

The “if” statement

如果判斷式為真,執行程式碼。程式碼建議加上 {...} 增加可讀性。

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) alert( 'You are right!' );

Boolean conversion

if statement 會將判斷式結果轉為布林值。

Value

Becomes…

0, null, undefined, NaN, ""

false

any other value

true

可以提前將判斷式存在變數中。

let cond = (year == 2015); // equality evaluates to true or false

if (cond) {
  ...
}

The “else” clause

當判斷式為錯誤,執行 else 的程式碼。

Several conditions: “else if”

Conditional operator ‘?’

可以用 ternary operator ? 代替 if statement。用在返回一個值,而非執行一段程式。

Multiple ‘?’

Non-traditional use of ‘?’

ternary operator ? 用在返回一個值,而非執行一段程式。

Last updated

Was this helpful?