Making Decisions: if, else, and switch
Code that always does the same thing is a vending machine with one button. Decisions give it a menu.
Every morning you make small decisions without thinking. Is it raining? Take an umbrella. Is it cold? Grab a jacket. Is it a weekday? Set an alarm. Otherwise, sleep in.
Your code needs to make decisions like that too. Is the shop open? Show the "Order now" button. Is the cart empty? Show a friendly message instead of a total. That's what this lesson is about.
if: do this only when...
const hour = 9;
if (hour >= 7) {
console.log('The bakery is open!');
}Read it as English: "If the hour is 7 or later, log that the bakery is open."
- The condition goes in parentheses. It's anything that gives a yes or no, like the comparisons from Operators and Comparisons.
- The code to run goes inside the curly braces, called a block. It only runs when the condition is truthy.
else: otherwise...
if (hour >= 7) {
console.log('The bakery is open!');
} else {
console.log('Sorry, we open at 7.');
}Exactly one of the two blocks runs. Never both, never neither. It's a fork in the road.
else if: more than two roads
const hour = 18;
if (hour < 7) {
console.log('Not open yet.');
} else if (hour < 17) {
console.log('Open!');
} else {
console.log('Closed for the day.');
}JavaScript checks each condition in order, from the top, and runs the first block whose condition is true. Then it skips the rest. Picture going through a checklist and stopping at the first "yes."
That "first match wins" rule means order matters. If you checked hour < 17 before hour < 7, a 5am visitor would be told the shop is open, because 5 is also less than 17.
Checking several things at once
Combine conditions with the && and || from the last lesson:
const hour = 10;
const isHoliday = false;
if (hour >= 7 && hour < 17 && !isHoliday) {
console.log('Come on in!');
}And remember truthy and falsy? You can check whether a value "exists" directly:
const typedName = '';
if (typedName) {
console.log(`Welcome, ${typedName}!`);
} else {
console.log('Please enter your name.');
}An empty string is falsy, so the else runs.
switch: matching exact values
When you're comparing one value against a list of specific options, a long chain of else if gets repetitive. switch reads more like a menu:
const day = 'Saturday';
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Weekend hours: 8am to 2pm.');
break;
case 'Monday':
console.log('Closed on Mondays.');
break;
default:
console.log('Weekday hours: 7am to 5pm.');
}switch (day)names the value to check.- Each
caseis one possible value. It compares with===, so types must match. defaultruns when no case matches, like the finalelse.breakmeans "I'm done, leave the switch."
That break is the famous trap. Leave it out, and JavaScript doesn't stop at the end of the matching case. It falls through and runs the next case's code too, and the next, until it hits a break or the end. Sometimes you want that on purpose, like 'Saturday' and 'Sunday' sharing one answer above. Most of the time, a missing break is a bug.
The ternary: a one-line choice
For small either-or choices, especially when you're picking between two values, there's a shortcut:
const loavesLeft = 0;
const label = loavesLeft > 0 ? 'In stock' : 'Sold out';
console.log(label); // 'Sold out'Read it as a question: "Are there loaves left? If yes, 'In stock'. If no, 'Sold out'." The pattern is condition ? valueIfTrue : valueIfFalse. It's called the ternary operator because it has three parts.
Use it for simple choices between two values. If you find yourself nesting one ternary inside another, switch back to if and else. Clear beats clever.
Always use the braces
JavaScript lets you leave off the curly braces when a block has just one line:
if (hour >= 7) console.log('Open!');It works, but it's a trap waiting for the day someone adds a second line and expects it to be part of the if. It won't be. Always write the braces. Your future self will thank you.
Try it
This bakery sign uses the current hour on your computer, so the answer depends on when you run it.
HTML
JavaScript
Preview
Console
Nothing logged yet. Anything you pass to console.log() shows up here.
Try it yourself
- Replace
new Date().getHours()with a fixed number, like6, then12, then20, and check each message. - Change
dayto'Monday'. Which block runs, and why doesn't the hour matter anymore? - Rewrite the day check as a
switchwith a special message for'Saturday'. Then remove onebreakon purpose and see what falls through.
Check your understanding
Up next
Decisions let your code choose. Next, you'll make it repeat: counting down, going through every item in a list, doing something until a condition changes. That's Loops.
