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.
1// Basic if statement2let temperature = 25;34if (temperature > 30) {5 console.log("It's hot outside!");6}78// The code inside the if block only runs if the condition is true9// 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.
1// if...else statement2let temperature = 25;34if (temperature > 30) {5 console.log("It's hot outside!");6} else {7 console.log("It's not that hot today."); // This will run8}910// You can also check for specific ranges11if (temperature > 30) {12 console.log("It's hot outside!");13} else if (temperature > 20) {14 console.log("It's warm outside."); // This will run15} 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.
1// switch statement2let day = "Monday";34switch (day) {5 case "Monday":6 console.log("Start of the work week."); // This will run7 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}2829// 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.
1// Ternary operator syntax: condition ? expressionIfTrue : expressionIfFalse2let age = 20;3let canVote = age >= 18 ? "Yes" : "No";45console.log("Can this person vote? " + canVote); // "Can this person vote? Yes"67// Equivalent if...else statement8let 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.
1// Basic for loop2// for (initialization; condition; increment/decrement)3for (let i = 0; i < 5; i++) {4 console.log("Count: " + i); // Prints numbers 0 through 45}67// Looping through an array8let fruits = ["apple", "banana", "orange", "mango"];910for (let i = 0; i < fruits.length; i++) {11 console.log("Fruit: " + fruits[i]);12}1314// Counting backwards15for (let i = 10; i > 0; i--) {16 console.log(i); // Countdown: 10, 9, 8, ..., 117}
The for...of Loop
The for...of
loop is a simpler way to iterate over arrays and other iterable objects.
1// for...of loop with an array2let fruits = ["apple", "banana", "orange", "mango"];34for (let fruit of fruits) {5 console.log("Fruit: " + fruit);6}78// for...of with a string (iterates over each character)9let greeting = "Hello";1011for (let char of greeting) {12 console.log(char); // Prints: H, e, l, l, o13}
The for...in Loop
The for...in
loop is designed to iterate over the properties of an object.
1// for...in loop with an object2let person = {3 name: "John",4 age: 30,5 job: "Developer"6};78for (let key in person) {9 console.log(key + ": " + person[key]);10}11// Prints:12// name: John13// age: 3014// job: Developer1516// Be careful using for...in with arrays17// It iterates over indices (as strings) and any custom properties18let numbers = [10, 20, 30];19numbers.someProperty = "Hello";2021for (let key in numbers) {22 console.log(key + ": " + numbers[key]);23}24// Prints:25// 0: 1026// 1: 2027// 2: 3028// someProperty: Hello
for...of vs for...in
for...of: Use for arrays when you want the actual values
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
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.
1// while loop2let count = 0;34while (count < 5) {5 console.log("Count: " + count);6 count++; // Don't forget to increment, or you'll have an infinite loop!7}89// Using while to process data until a condition is met10let dice = 0;1112while (dice !== 6) {13 dice = Math.floor(Math.random() * 6) + 1; // Random number between 1 and 614 console.log("You rolled: " + dice);15}1617console.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.
1// do...while loop2let count = 0;34do {5 console.log("Count: " + count);6 count++;7} while (count < 5);89// Even if the condition is false initially, the code runs at least once10let x = 10;1112do {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.
1// Using break to exit a loop early2for (let i = 0; i < 10; i++) {3 console.log(i);45 if (i === 5) {6 console.log("Breaking the loop at i = 5");7 break; // Exit the loop when i is 58 }9}10// Prints: 0, 1, 2, 3, 4, 5, "Breaking the loop at i = 5"1112// Finding an element in an array13let numbers = [1, 3, 5, 7, 9, 11];14let searchFor = 7;15let foundIndex = -1;1617for (let i = 0; i < numbers.length; i++) {18 if (numbers[i] === searchFor) {19 foundIndex = i;20 break; // No need to continue searching21 }22}2324console.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.
1// Using continue to skip iterations2for (let i = 0; i < 10; i++) {3 // Skip odd numbers4 if (i % 2 !== 0) {5 continue; // Skip the rest of this iteration6 }78 console.log("Even number: " + i);9}10// Prints: "Even number: 0", "Even number: 2", "Even number: 4", etc.1112// Filtering items in a loop13let scores = [75, 50, 85, 30, 90, 40];1415console.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 6019 }2021 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.
1// Nested loops2for (let i = 1; i <= 3; i++) {3 console.log("Outer loop iteration: " + i);45 for (let j = 1; j <= 3; j++) {6 console.log(" Inner loop iteration: " + j);7 }8}910// Creating a multiplication table11console.log("Multiplication Table (1-5):");1213for (let i = 1; i <= 5; i++) {14 let row = "";1516 for (let j = 1; j <= 5; j++) {17 row += (i * j) + "\t"; // \t is a tab character for spacing18 }1920 console.log(row);21}
Practice Exercises
Try these exercises to reinforce your understanding of JavaScript control flow:
// 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
, andswitch
statements - How to repeat code using
for
,for...of
,for...in
,while
, anddo...while
loops - How to control loop execution with
break
andcontinue
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 moreLearn how to create and use functions in JavaScript.
Learn moreLearn about arrays and how to work with collections of data.
Learn more