So far, every program you have written runs every line, top to bottom. Real programs need to make choices: show the "Game Over" screen only when lives reach 0, give a discount only if the cart is over $50. Conditional statements let your code run different actions depending on whether a condition is true or false.
The condition is almost always a comparison, from the last lesson:
let lives = 0;
if (lives === 0) {
console.log("Game Over");
}
JavaScript has five conditional tools. This lesson introduces each one, so you can recognize them and know which to reach for. The next section (JS If Conditions) gives each its own full lesson.
| Tool | Use it to | Full lesson |
|---|---|---|
| if | Run a block only if a condition is true | JS If |
| else | Run a different block if that same condition is false | JS If Else |
| else if | Test a new condition if the first one was false | JS If Else |
| switch | Pick one of many blocks by matching a value | JS Switch |
| ? : | Pick one of two values (shorthand for if...else) | JS Ternary |
Use if to run a block of code only when a condition is true. If it is false, the block is skipped and the program carries on after it.
if (condition) {
// code to run if the condition is true
}
let cartTotal = 62;
if (cartTotal > 50) {
console.log("You get free shipping!");
}
console.log("Thanks for shopping"); // always runs
if must be lowercase (If or IF is an error), and the condition must be inside parentheses. Watch the comparison too: if (lives = 0) assigns 0 instead of comparing, and the block never runs. Use ===.
Add else to run a different block when the same condition is false. Exactly one of the two blocks always runs, never both, never neither:
if (condition) {
// runs if the condition is true
} else {
// runs if the condition is false
}
let hour = 20;
if (hour < 18) {
console.log("Good day");
} else {
console.log("Good evening");
}
When there are more than two possibilities, chain else if to test a new condition when the one before it was false. JavaScript checks each condition in order, runs the first block whose condition is true, and skips all the rest. The final else catches everything that matched nothing.
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 is false and condition2 is true
} else {
// runs if both are false
}
let score = 84;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("Needs work");
}
84 is also >= 70, but that test is never reached. The first true condition wins, which is why the order of an else if chain matters: put the most specific test first.
Use switch when you compare one value against a list of possible exact matches. Each possible match is a case, and default handles anything not listed:
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
let day = "Sat";
switch (day) {
case "Sat":
console.log("Weekend!");
break;
case "Mon":
console.log("Back to school");
break;
default:
console.log("A weekday");
}
break ends the switch once a case has run. Leaving it out is a classic bug covered in the JS Switch lesson.
The conditional (ternary) operator is the only conditional that is an operator, which is why it lives in this Operators section. Instead of running blocks of code, it picks one of two values:
condition ? valueIfTrue : valueIfFalse
Read it as a question: "is the condition true? If so, this value; otherwise, that value." Here is the same decision both ways:
let age = 20;
// if...else version
let status1;
if (age >= 18) {
status1 = "adult";
} else {
status1 = "minor";
}
// ternary version: one line, same result
let status2 = age >= 18 ? "adult" : "minor";
console.log(status1, status2);
Use the ternary to choose between two simple values. When either side needs more than one statement, use if...else. The JS Ternary lesson shows where it shines and where it hurts readability.
| Situation | Reach for |
|---|---|
| Do something extra, or nothing | if |
| Exactly two paths | if...else |
| Several paths based on ranges (>, <) | if...else if...else |
| One value matched against many exact options | switch |
| Choosing between two values to store or show | ? : |
A game shows a different message for each of 6 difficulty names: "easy", "normal", "hard", and so on. Which tool fits best?
if aloneif...elseswitch? :switch is for. An else if chain would also work, but would repeat difficulty === six times.What does this log?
let temp = 95;
if (temp > 70) {
console.log("warm");
} else if (temp > 90) {
console.log("hot");
} else {
console.log("cool");
}
warm. 95 passes the first test, so that block runs and the rest are skipped. The "hot" branch can never run as written; put the > 90 test first to fix it.What does let label = 3 > 5 ? "big" : "small"; store in label?
"big""small"false33 > 5 is false, so the ternary picks the value after the colon.if that logs "Game Over" only when lives is 0. Run it with 3, then change it to 0 and run it againelse that logs how many lives are leftelse if chain that turns a temperature into "hot", "warm", or "cold". Test it with 95, 75, and 40isMember is true, price is 8, otherwise 10. Log price with isMember set to true, then false