Programs need to make decisions: show an error or a success message, unlock the next lesson or not, charge delivery or make it free. Conditionals let your code take different paths depending on values. This lesson covers if and else, how JavaScript decides what counts as true, switch, and the ternary operator.
if
An if statement runs a block of code only when its condition is true:
const score = 82;
if (score >= 70) {
console.log("You passed.");
}
// You passed.
The condition goes in brackets. The code to run goes in curly braces. If the condition is false, the block is skipped.
You can technically leave out the braces when the block is a single line, but do not. Adding a second line later without adding braces is a classic bug. Always use braces.
else and else if
else runs when the condition is false:
const stock = 0;
if (stock > 0) {
console.log("In stock");
} else {
console.log("Out of stock");
}
// Out of stock
Chain several conditions with else if. JavaScript checks them from top to bottom and runs only the first block whose condition is true:
const score = 64;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else if (score >= 60) {
grade = "C";
} else {
grade = "Fail";
}
console.log(grade);
// C
Order matters. Because the first true condition wins, check the most specific or highest range first. If score >= 60 came first, a score of 95 would get a C.
Combining conditions
Use the logical operators from lesson 5 to combine conditions:
const age = 16;
const hasConsent = true;
if (age >= 18 || (age >= 13 && hasConsent)) {
console.log("You can create an account.");
}
// You can create an account.
Brackets make the intent clear even where precedence would give the same result. If a condition grows long, give its parts names:
const isAdult = age >= 18;
const isTeenWithConsent = age >= 13 && hasConsent;
if (isAdult || isTeenWithConsent) {
console.log("You can create an account.");
}
The second version reads like a sentence and is easier to check.
Truthy and falsy values
The condition of an if does not have to be a boolean. JavaScript converts whatever you give it to true or false. Values that become false are called falsy. There are only a few:
| Falsy value | Type |
|---|---|
false | boolean |
0 and -0 | number |
0n | bigint |
"" (empty string) | string |
null | null |
undefined | undefined |
NaN | number |
Everything else is truthy, including some values that surprise people:
if ("0") console.log("'0' is truthy");
if ("false") console.log("'false' is truthy");
if ([]) console.log("[] is truthy");
if ({}) console.log("{} is truthy");
// '0' is truthy
// 'false' is truthy
// [] is truthy
// {} is truthy
A non-empty string is always truthy, whatever it says. An empty array or object is truthy too, because it is an object. (Those one-line if statements without braces are just for this demonstration.)
You can see how any value converts with Boolean():
console.log(Boolean(""));
// false
console.log(Boolean("hello"));
// true
console.log(Boolean(0));
// false
Using truthiness well
Truthy checks are a handy way to test whether something exists:
const nickname = "";
if (nickname) {
console.log(`Hello, ${nickname}`);
} else {
console.log("Hello, guest");
}
// Hello, guest
But they can hide bugs when 0 or "" is a valid value:
const itemsInBasket = 0;
if (!itemsInBasket) {
console.log("Basket data is missing");
}
// Basket data is missing
The basket is empty, not missing. Be explicit when the difference matters:
if (itemsInBasket === undefined) {
console.log("Basket data is missing");
} else if (itemsInBasket === 0) {
console.log("Your basket is empty");
}
// Your basket is empty
To check that an array has items, test its length, because an empty array is truthy: if (list.length > 0).
Early returns and guard clauses
Deeply nested if statements are hard to read. Inside a function, you can often check for problem cases first and leave early. Functions are covered in lesson 10, but the pattern is worth seeing now:
function describeOrder(order) {
if (!order) {
return "No order";
}
if (order.items === 0) {
return "Empty order";
}
return `Order with ${order.items} items`;
}
console.log(describeOrder({ items: 3 }));
// Order with 3 items
Each check handles one case and gets out of the way, so the main logic sits at the end without extra indentation.
switch
A switch compares one value against several fixed options. It suits cases where you would otherwise write a long chain of else if (x === ...):
const day = "sat";
let opening;
switch (day) {
case "sat":
case "sun":
opening = "10:00 to 16:00";
break;
case "mon":
opening = "Closed";
break;
default:
opening = "09:00 to 17:30";
}
console.log(opening);
// 10:00 to 16:00
How it works:
switchcomparesdaywith eachcaseusing strict equality,===.- When a case matches, it runs the code from that point on.
breakstops it. Withoutbreak, execution falls through into the next case's code.defaultruns if no case matches. It is optional but usually a good idea.
The "sat" and "sun" cases share code deliberately, by stacking them with nothing between. That is the one good use of fall-through. Forgetting a break elsewhere is a common bug, so always check each case ends with break or return.
For simple value-to-value lookups, an object is often neater than a switch: const labels = { sat: "Weekend", sun: "Weekend" }; labels[day]. Objects are covered in lesson 13.
The ternary operator
The conditional (ternary) operator chooses between two values in a single expression:
const stock = 3;
const label = stock > 0 ? "In stock" : "Out of stock";
console.log(label);
// In stock
Read it as: "if stock > 0, then "In stock", otherwise "Out of stock"". It is called ternary because it takes three parts.
Use it when you are choosing between two values, especially inside a template literal:
const count = 1;
console.log(`You have ${count} ${count === 1 ? "lesson" : "lessons"} left.`);
// You have 1 lesson left.
Do not use it for actions with side effects, or nest one ternary inside another. If you need more than one condition, an if statement is clearer.
Which to choose
| Situation | Use |
|---|---|
| Run different code depending on a condition | if / else |
| Several ranges or complex conditions | if / else if / else |
| One value compared against many fixed options | switch, or an object lookup |
| Choose between two values in an expression | Ternary ? : |
Summary
ifruns a block when its condition is truthy;else ifandelsehandle the other cases, and the first true condition wins.- Always use braces, and give complex conditions meaningful names.
- The falsy values are
false,0,-0,0n,"",null,undefinedandNaN. Everything else, including"0",[]and{}, is truthy. - Be explicit when
0or""are valid values; checklengthfor arrays. switchcompares with===and falls through withoutbreak.- Use the ternary operator to choose between two values, not for actions or nested logic.