Progress4 of 20 topics

20% complete

JavaScript Control Flow

Control flow is how we direct the execution of our code based on certain conditions. It's like giving your program a brain to make decisions and repeat tasks. In this tutorial, we'll explore conditional statements and loops in JavaScript.

Real-World Analogy

Think of control flow like this:

  • Conditional statements are like traffic lights that direct traffic based on conditions
  • Loops are like assembly lines that repeat the same task until all items are processed

Conditional Statements

Conditional statements allow your program to make decisions based on certain conditions.

The if Statement

The if statement is the most basic conditional statement. It executes a block of code if a specified condition is true.

JavaScript
1// Basic if statement
2let temperature = 25;
3
4if (temperature > 30) {
5 console.log("It's hot outside!");
6}
7
8// The code inside the if block only runs if the condition is true
9// In this case, nothing will be printed because 25 is not greater than 30

The if...else Statement

The if...else statement executes one block of code if a condition is true and another block if it's false.

JavaScript
1// if...else statement
2let temperature = 25;
3
4if (temperature > 30) {
5 console.log("It's hot outside!");
6} else {
7 console.log("It's not that hot today."); // This will run
8}
9
10// You can also check for specific ranges
11if (temperature > 30) {
12 console.log("It's hot outside!");
13} else if (temperature > 20) {
14 console.log("It's warm outside."); // This will run
15} else if (temperature > 10) {
16 console.log("It's cool outside.");
17} else {
18 console.log("It's cold outside.");
19}

⚠️ Important Note

In an if...else if...else chain, JavaScript stops checking conditions once it finds a true condition. This means only the first matching condition's code block will run.

The switch Statement

The switch statement is useful when you need to compare a value against multiple possible cases.

JavaScript
1// switch statement
2let day = "Monday";
3
4switch (day) {
5 case "Monday":
6 console.log("Start of the work week."); // This will run
7 break;
8 case "Tuesday":
9 console.log("Second day of the week.");
10 break;
11 case "Wednesday":
12 console.log("Middle of the work week.");
13 break;
14 case "Thursday":
15 console.log("Almost the weekend.");
16 break;
17 case "Friday":
18 console.log("Last day of the work week.");
19 break;
20 case "Saturday":
21 case "Sunday":
22 console.log("It's the weekend!");
23 break;
24 default:
25 console.log("Not a valid day.");
26 break;
27}
28
29// The break statement is important - without it, execution would "fall through"
30// to the next case, even if it doesn't match

Conditional (Ternary) Operator

The ternary operator is a shorthand way to write simple if...else statements.

JavaScript
1// Ternary operator syntax: condition ? expressionIfTrue : expressionIfFalse
2let age = 20;
3let canVote = age >= 18 ? "Yes" : "No";
4
5console.log("Can this person vote? " + canVote); // "Can this person vote? Yes"
6
7// Equivalent if...else statement
8let canVoteIfElse;
9if (age >= 18) {
10 canVoteIfElse = "Yes";
11} else {
12 canVoteIfElse = "No";
13}

Loops

Loops allow you to repeat code multiple times. They're essential for tasks like processing arrays or performing an action a specific number of times.

The for Loop

The for loop repeats a block of code a specified number of times.

JavaScript
1// Basic for loop
2// for (initialization; condition; increment/decrement)
3for (let i = 0; i < 5; i++) {
4 console.log("Count: " + i); // Prints numbers 0 through 4
5}
6
7// Looping through an array
8let fruits = ["apple", "banana", "orange", "mango"];
9
10for (let i = 0; i < fruits.length; i++) {
11 console.log("Fruit: " + fruits[i]);
12}
13
14// Counting backwards
15for (let i = 10; i > 0; i--) {
16 console.log(i); // Countdown: 10, 9, 8, ..., 1
17}

The for...of Loop

The for...of loop is a simpler way to iterate over arrays and other iterable objects.

JavaScript
1// for...of loop with an array
2let fruits = ["apple", "banana", "orange", "mango"];
3
4for (let fruit of fruits) {
5 console.log("Fruit: " + fruit);
6}
7
8// for...of with a string (iterates over each character)
9let greeting = "Hello";
10
11for (let char of greeting) {
12 console.log(char); // Prints: H, e, l, l, o
13}

The for...in Loop

The for...in loop is designed to iterate over the properties of an object.

JavaScript
1// for...in loop with an object
2let person = {
3 name: "John",
4 age: 30,
5 job: "Developer"
6};
7
8for (let key in person) {
9 console.log(key + ": " + person[key]);
10}
11// Prints:
12// name: John
13// age: 30
14// job: Developer
15
16// Be careful using for...in with arrays
17// It iterates over indices (as strings) and any custom properties
18let numbers = [10, 20, 30];
19numbers.someProperty = "Hello";
20
21for (let key in numbers) {
22 console.log(key + ": " + numbers[key]);
23}
24// Prints:
25// 0: 10
26// 1: 20
27// 2: 30
28// someProperty: Hello

for...of vs for...in

for...of: Use for arrays when you want the actual values

JavaScript
let arr = [1, 2, 3];
for (let value of arr) {
console.log(value); // 1, 2, 3
}

for...of vs for...in

for...in: Use for objects when you want the property names

JavaScript
let obj = {a: 1, b: 2};
for (let key in obj) {
console.log(key); // "a", "b"
}

The while Loop

The while loop repeats a block of code as long as a specified condition is true.

JavaScript
1// while loop
2let count = 0;
3
4while (count < 5) {
5 console.log("Count: " + count);
6 count++; // Don't forget to increment, or you'll have an infinite loop!
7}
8
9// Using while to process data until a condition is met
10let dice = 0;
11
12while (dice !== 6) {
13 dice = Math.floor(Math.random() * 6) + 1; // Random number between 1 and 6
14 console.log("You rolled: " + dice);
15}
16
17console.log("Finally rolled a 6!");

⚠️ Beware of Infinite Loops

Always make sure your loop condition will eventually become false, or you'll create an infinite loop that can crash your program. In the browser, this might freeze your tab or show a "script is taking too long" error.

The do...while Loop

The do...while loop is similar to the while loop, but it always executes the code block at least once before checking the condition.

JavaScript
1// do...while loop
2let count = 0;
3
4do {
5 console.log("Count: " + count);
6 count++;
7} while (count < 5);
8
9// Even if the condition is false initially, the code runs at least once
10let x = 10;
11
12do {
13 console.log("This runs once even though the condition is false");
14} while (x < 5);

Breaking and Continuing Loops

Sometimes you need to control the flow within a loop. JavaScript provides two statements for this:

The break Statement

The break statement immediately exits the loop.

JavaScript
1// Using break to exit a loop early
2for (let i = 0; i < 10; i++) {
3 console.log(i);
4
5 if (i === 5) {
6 console.log("Breaking the loop at i = 5");
7 break; // Exit the loop when i is 5
8 }
9}
10// Prints: 0, 1, 2, 3, 4, 5, "Breaking the loop at i = 5"
11
12// Finding an element in an array
13let numbers = [1, 3, 5, 7, 9, 11];
14let searchFor = 7;
15let foundIndex = -1;
16
17for (let i = 0; i < numbers.length; i++) {
18 if (numbers[i] === searchFor) {
19 foundIndex = i;
20 break; // No need to continue searching
21 }
22}
23
24console.log("Found at index: " + foundIndex); // "Found at index: 3"

The continue Statement

The continue statement skips the current iteration and moves to the next one.

JavaScript
1// Using continue to skip iterations
2for (let i = 0; i < 10; i++) {
3 // Skip odd numbers
4 if (i % 2 !== 0) {
5 continue; // Skip the rest of this iteration
6 }
7
8 console.log("Even number: " + i);
9}
10// Prints: "Even number: 0", "Even number: 2", "Even number: 4", etc.
11
12// Filtering items in a loop
13let scores = [75, 50, 85, 30, 90, 40];
14
15console.log("Passing scores (60 or higher):");
16for (let i = 0; i < scores.length; i++) {
17 if (scores[i] < 60) {
18 continue; // Skip scores less than 60
19 }
20
21 console.log("- " + scores[i]);
22}
23// Prints: "Passing scores (60 or higher):", "- 75", "- 85", "- 90"

Nested Loops

You can place loops inside other loops to work with multi-dimensional data or to perform complex iterations.

JavaScript
1// Nested loops
2for (let i = 1; i <= 3; i++) {
3 console.log("Outer loop iteration: " + i);
4
5 for (let j = 1; j <= 3; j++) {
6 console.log(" Inner loop iteration: " + j);
7 }
8}
9
10// Creating a multiplication table
11console.log("Multiplication Table (1-5):");
12
13for (let i = 1; i <= 5; i++) {
14 let row = "";
15
16 for (let j = 1; j <= 5; j++) {
17 row += (i * j) + "\t"; // \t is a tab character for spacing
18 }
19
20 console.log(row);
21}

Practice Exercises

Try these exercises to reinforce your understanding of JavaScript control flow:

JavaScript
// 1. FizzBuzz
// Write a program that prints numbers from 1 to 100
// For multiples of 3, print "Fizz" instead of the number
// For multiples of 5, print "Buzz" instead of the number
// For multiples of both 3 and 5, print "FizzBuzz"
// 2. Grade Calculator
// Create a function that takes a score (0-100) and returns a grade:
// 90-100: 'A'
// 80-89: 'B'
// 70-79: 'C'
// 60-69: 'D'
// Below 60: 'F'
// 3. Sum of Even Numbers
// Calculate the sum of all even numbers from 1 to 100 using a loop
// 4. Star Pattern
// Use nested loops to print this pattern:
// *
// **
// ***
// ****
// *****

Summary

In this tutorial, you've learned:

  • How to make decisions in your code using if, if...else, and switch statements
  • How to repeat code using for, for...of, for...in, while, and do...while loops
  • How to control loop execution with break and continue statements
  • How to use nested loops for more complex iterations

Control flow is a fundamental concept in programming that allows you to create dynamic and responsive applications. In the next tutorial, you'll learn about functions, which will help you organize your code into reusable blocks.

Related Tutorials

Learn about different operators in JavaScript for calculations and comparisons.

Learn more

Learn how to create and use functions in JavaScript.

Learn more

Learn about arrays and how to work with collections of data.

Learn more