| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/if...else | [Back] [Original] |
Get to know MDN better
This feature is well established and works across many devices and browser versions. Its been available across browsers since 20157.
if
function testNum(a) {
let result;
if (a > 0) {
result = "positive";
} else {
result = "NOT positive";
}
return result;
}
console.log(testNum(-5));
// Expected output: "NOT positive"
if (condition)
statement1
// With an else clause
if (condition)
statement1
else
statement2
conditionstatement1if (conditions)(statements)(nested) if (statements)(block)(empty statement)
statement2else (block)(nested)
if...else else if JavaScript elseif ()
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
//
else
statementN
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
statement3
//
({ ... }) if
if (condition) {
statements1
} else {
statements2
}
Boolean true false false undefined null 0 NaN ("") false
var b = new Boolean(false);
if (b) // this condition is truthy
if...elseif (cipherChar === fromChar) {
result += toChar;
x++;
} else {
result += clearChar;
}
else if JavaScript elseif else if
if (x > 50) {
/* do something */
} else if (x > 5) {
/* do something */
} else {
/* do something */
}
( assignment )( equality )
if ((x = y)) {
/* do the right thing */
}
if (x = y) {
// do something
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-if-statement |
This page was last modified on 2026526 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |