[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/if...else [Back]  [Original]

if...else - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

if...else

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 20157.

if

In this article

function testNum(a) {
  let result;
  if (a > 0) {
    result = "positive";
  } else {
    result = "NOT positive";
  }
  return result;
}

console.log(testNum(-5));
// Expected output: "NOT positive"

js
if (condition)
  statement1

// With an else clause
if (condition)
  statement1
else
  statement2
condition

statement1

if (conditions)(statements)(nested) if (statements)(block)(empty statement)

statement2

else (block)(nested)

if...else else if JavaScript elseif ()

js
if (condition1)
   statement1
else if (condition2)
   statement2
else if (condition3)
   statement3
// 
else
   statementN

js
if (condition1)
  statement1
else
  if (condition2)
    statement2
  else
    if (condition3)
      statement3
// 

({ ... }) if

js
if (condition) {
  statements1
} else {
  statements2
}

Boolean true false false undefined null 0 NaN ("") false

js
var b = new Boolean(false);
if (b) // this condition is truthy

if...else

js
if (cipherChar === fromChar) {
  result += toChar;
  x++;
} else {
  result += clearChar;
}

else if

JavaScript elseif else if

js
if (x > 50) {
  /* do something */
} else if (x > 5) {
  /* do something */
} else {
  /* do something */
}

( assignment )( equality )

js
if ((x = y)) {
  /* do the right thing */
}

js
if (x = y) {
  // do something
}

Specification
ECMAScript 2027 LanguageSpecification
# sec-if-statement


Web Proxy Viewer  |  New URL  |  Original Page