By the end of this lesson, learners will:
if
, else
, and switch
When you write a JavaScript program, the browser reads your code from top to bottom, left to right, one line at a time.
This is called the default control flow.
Example:
console.log("Line 1");
console.log("Line 2");
console.log("Line 3");
Output:
Line 1
Line 2
Line 3
Real programs often need to make decisions, like:
This is where control flow tools come in.
JavaScript provides special keywords to change the flow of execution based on:
if
, else
, else if
)switch
)for
, while
— covered in the next module)Without control flow:
console.log("Always runs");
With control flow:
if (userLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
You’ll learn these in this module:
Keyword/Structure | Purpose |
---|---|
if | Check a condition and run code if it’s true |
else | Run different code if the if condition is false |
else if | Add more specific conditions |
switch | Compare one value to many possible values |
break | Exit a switch block early |
default | Run fallback code in a switch block |
Think of a traffic light:
That’s exactly what we’ll be doing with JavaScript:
let light = "green";
if (light === "green") {
console.log("Go");
} else if (light === "yellow") {
console.log("Slow down");
} else {
console.log("Stop");
}
let temperature = 32;
if (temperature < 0) {
console.log("It's freezing!");
} else if (temperature < 30) {
console.log("It's a nice day.");
} else {
console.log("It's hot outside!");
}
🧠 This program:
temperature
)Without control flow, all your programs would do the exact same thing every time — no interaction, no customization, no intelligence.
Control flow lets your program:
if
, else
, and switch
help your program make decisions.