Control flow allows your programs to make decisions and respond to different conditions.
Without control flow, every script would run the same way every time.
In this lesson, we introduce if statements, else blocks, switch cases, and the ternary operator.
if Statement
The if statement runs a block of code only when a condition is true.
let age = 20;
if (age >= 18) {
console.log("You are an adult");
}if ... else
Use else to run a different block when the condition is false.
let score = 55;
if (score >= 60) {
console.log("Passed");
} else {
console.log("Failed");
}else if Chain
Use else if for multiple conditions.
let temperature = 28;
if (temperature > 30) {
console.log("Too hot");
} else if (temperature >= 20) {
console.log("Perfect weather");
} else {
console.log("Too cold");
}switch Statement
Switch is useful when you need to compare a value against many possible matches.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Almost weekend");
break;
default:
console.log("Midweek day");
}Ternary Operator
A shorter form of an if ... else expression.
let isLoggedIn = true;
let message = isLoggedIn
? "Welcome back!"
: "Please log in";
console.log(message);This is commonly used in UI logic.
Truthy and Falsy Values
JavaScript treats some values as "true" or "false" in boolean contexts.
Falsy values:
- false
- 0
- ""
- null
- undefined
- NaN
Everything else is truthy.
if ("") {
console.log("This won't run");
}
if ("Hello") {
console.log("This will run");
}Summary
In this lesson, you learned:
- How if, else, and else if work
- How switch statements simplify multiple comparisons
- How to write compact logic with the ternary operator
- How truthy and falsy values behave in JavaScript
In the next lesson, we will explore functions — one of the most important building blocks in JavaScript.