Control Flow - If Statements and Loops
What is Control Flow?
Control flow is the order in which JavaScript executes statements. By default, code runs top to bottom. Control flow structures let you branch (run different code depending on conditions) and repeat (run the same code multiple times).
If / Else If / Else
The if statement runs a block of code only when a condition is truthy:
const score = 78;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else if (score >= 50) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Output: "Grade: B"
You can chain as many else if blocks as needed. Only the first matching branch executes.
Truthy and Falsy Values
JavaScript automatically converts conditions to boolean. The following values are falsy (they behave like false):
false, 0, "", null, undefined, NaN
Everything else is truthy. This lets you write concise conditions:
const username = "";
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please enter your name"); // This runs because "" is falsy
}
Switch Statements
A switch statement is useful when you have many branches based on a single value:
const day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Weekday");
break;
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Unknown day");
}
Always include a break statement at the end of each case to stop it from falling through to the next case. The default case runs when no case matches.
For Loops
A for loop runs a block of code a specific number of times:
// Syntax: for (initialisation; condition; update)
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}
// Outputs: 0, 1, 2, 3, 4
A practical example — looping through an array:
const fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
While Loops
A while loop runs as long as a condition is truthy:
let attempts = 0;
while (attempts < 3) {
console.log("Attempt:", attempts + 1);
attempts++;
}
// Outputs: Attempt: 1, Attempt: 2, Attempt: 3
Be careful with while loops — if the condition never becomes false, you get an infinite loop that crashes the browser.
for...of (Recommended for Arrays)
The for...of loop iterates directly over the values of an array or other iterable, without needing an index:
const courses = ["HTML", "CSS", "JavaScript", "React"];
for (const course of courses) {
console.log("Learning:", course);
}
// Learning: HTML
// Learning: CSS
// Learning: JavaScript
// Learning: React
Use for...of whenever you need to loop through an array and do not need the index.
break and continue
break exits the loop entirely:
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Stop the loop when i reaches 5
console.log(i);
}
// Outputs: 0, 1, 2, 3, 4
continue skips the current iteration and moves to the next:
for (let i = 0; i < 5; i++) {
if (i === 2) continue; // Skip when i is 2
console.log(i);
}
// Outputs: 0, 1, 3, 4
Key Takeaways
- if/else if/else branches execution based on conditions evaluated as truthy or falsy
- Switch statements cleanly handle multiple branches based on a single value
- for loops are ideal when you know how many iterations you need
- while loops run as long as a condition is truthy — always ensure the condition eventually becomes false
- for...of is the cleanest way to loop over array values without needing an index
- break exits a loop; continue skips to the next iteration
Practice Exercise
- Write a function
getFeelingDescription(temp)that returns "Hot" for temps above 30, "Warm" for 20-30, "Cool" for 10-19, and "Cold" below 10 - Use a
forloop to print the numbers 1 through 10, but usecontinueto skip multiples of 3 - Create an array of student names and use
for...ofto log a personalised message for each - Write a
whileloop that counts down from 5 to 1 then logs "Blast off!"
Try it yourself
Key Takeaways
- if/else if/else chains allow branching logic based on conditions evaluated as truthy or falsy
- Falsy values in JavaScript are: false, 0, empty string, null, undefined, and NaN
- Switch statements are cleaner than long if/else chains when comparing a single value against many options
- for loops are best when you know the number of iterations; while loops are best when you don't
- for...of provides the cleanest syntax for iterating over array elements without needing an index
- break exits a loop entirely; continue skips the current iteration and proceeds to the next
Quick Quiz
1.Which of the following values is falsy in JavaScript?
2.What happens if you forget the break statement in a switch case?
3.What is the main advantage of for...of over a traditional for loop when iterating over arrays?
4.What does the continue statement do inside a loop?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx