An if on its own either runs its block or does nothing. Often you need a second option: do this, otherwise do that. Adding else gives you that fallback, and chaining else if lets you choose between as many options as you need.
Use else to give a block of code to run when the condition is false:
if (condition) {
// runs if the condition is true
} else {
// runs if the condition is false
}
let hour = 20;
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
console.log(greeting);
With if...else, exactly one of the two blocks runs: never both, never neither. That is the key difference from two separate if statements.
Notice that else has no condition of its own. It simply means "in every other case". Writing else (hour >= 18) { ... } is a SyntaxError.
Use else if to test a new condition when the one before it was false:
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 is false and condition2 is true
} else {
// runs if condition1 and condition2 are both false
}
let time = 14;
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
console.log(greeting);
You can chain as many else if blocks as you need. JavaScript checks them top to bottom, runs the first one whose condition is true, and skips everything after it:
let score = 74;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("F");
}
74 fails the first two tests, passes >= 70, prints "C", and the rest of the chain is skipped. Notice the score >= 70 test did not also need score < 80: by the time it is checked, we already know the score is under 80, or the B branch would have caught it.
score >= 70, every score of 70 or more (even 100) would get a "C", and the A and B branches could never run. Put the most specific (strictest) test first.
An if...else if chain does not need a final else. Leave it off when there is nothing to do if none of the conditions match:
let role = "guest";
if (role === "admin") {
console.log("Admin panel loaded");
} else if (role === "teacher") {
console.log("Gradebook loaded");
}
// a guest matches neither, so nothing extra happens
A final else is useful as a catch-all for unexpected values, though. Many programmers add one that logs a warning, so a typo like "Admin" does not fail silently.
Math.random() gives a random decimal number from 0 up to (but not including) 1. Since it is below 0.5 about half the time, it makes a quick coin flip:
let result;
if (Math.random() < 0.5) {
result = "Heads";
} else {
result = "Tails";
}
console.log(result);
JS Math Random covers Math.random() fully, including how to get random whole numbers.
An if...else can go inside another one when a second question only makes sense after the first is answered:
let age = 20;
let hasId = false;
if (age >= 18) {
if (hasId) {
console.log("Entry allowed");
} else {
console.log("ID required");
}
} else {
console.log("Must be 18+");
}
Each else belongs to the nearest if above it at the same level. Consistent indentation is what lets you see which is which. Keep nesting to two levels at most; beyond that, look for a way to flatten it with else if or &&.
// Classify a body temperature in °C
let temp = 37.9;
let status;
if (temp >= 38) {
status = "fever";
} else if (temp >= 36) {
status = "normal";
} else {
status = "low";
}
console.log(temp + "°C is " + status);
With if (...) { A } else { B }, how many of the blocks can run?
What does this log?
let speed = 75;
if (speed > 50) {
console.log("fast");
} else if (speed > 70) {
console.log("very fast");
} else {
console.log("slow");
}
fast. 75 passes the first test, so the chain stops there. "very fast" can never print as written; swap the first two tests so the stricter one (> 70) comes first.What is wrong with this code?
if (score >= 60) {
result = "pass";
} else (score < 60) {
result = "fail";
}
else cannot have a condition. Either remove (score < 60), since else already means "otherwise", or change it to else if. As written it is a SyntaxError.if...else that logs "pass" or "fail" for score, using 60 as the cutoffelse if for "distinction" when the score is 90 or more. Where in the chain must it go?