JavaScript Control Flow For Beginners

What is Control Flow

Control flow refers to the order in which statements, functions, and instructions are executed when running a program. It guides the execution of a program. Some benefits of control flow include:

  • Error and Event handling

    In interactive applications, control flow is essential for managing user actions and events and handling unexpected situations and errors.

  • Logical execution

    Control flow helps developers determine the logical flow of their program. Developers can define conditions and execute code based on these conditions.

  • Dynamic behavior

    Control flow allows for dynamic behavior in applications by performing actions based on user actions and other conditions.

Control Flow Structure

Conditional statements ( "if", "else", "else if")

Conditional statements execute code based on a given condition. These statements allow you to control the flow of your program.

if statements

// if statements
let food = "rice";

if(food == "rice"){
 console.log("Purchase food")
}
  • For the code above, the food variable is declared and has a value of rice assigned to it.

  • The if statement checks if the food is rice before purchasing it.

  • "Purchase food" is logged into the console because the value of 'food' is set to rice.

else statements

// if statements
let food = "beans";

if(food == "rice"){
 console.log("Purchase food")
} else{
  console.log("Fast for the day")
}
  • In the example above, food has a value of beans assigned to it. The if statement checks if the value of food is equal to rice.

  • The condition for the if statement is false, so the else condition runs.

  • Since the else statement evaluates to true, the message "fast for the day" is logged into the console.

Our next example explains the usage of an else if statement. To piece together all we've learned, let's create a program that groups movies based on ratings using conditional statements

let userRating = 4;
// Create a variable named userRating and set its value to 4

if (userRating >= 4.5) {
  console.log("Great movie, would see again!")
} else if ( userRating >= 3.5) {
  console.log("Good movie")
} else if ( userRating >= 2.5) {
  console.log("Mid, would recommend to my siblings")
} else {
  console.log("Too bad, arrest the producer, acting crew, everyone")
}

In the example code above, we declare a variable named "userRating" and assign it a value of "4"

  • The first if statement checks if the value of the userRating is greater than or equal to "4.5" using the >= operator. If the condition is true, the message "Great movie, would see again!" is logged into the console.

  • The second conditional statement (else if statement) checks if the userRating is greater than or equal to "3.5". If true, "good movie" is logged into the console.

  • The third conditional statement will display the message "mid, would recommend to my siblings" if evaluated to be true. The last condition (else) will return true if all preceding conditions are false.

  • For this particular example, since the userRating is "4", the second statement (else if) returns true. The message "good movie" is logged into the console.

  • For practice, change the value of the userRating from "4" to "1" in your code example and look out for the message in the console. What does it say?

Switch Statements

Switch statements are an alternative to if-else statements. Below is an example:

let dayOfWeek = 4;

      switch (dayOfWeek) {
        case 1:
          console.log("Monday");
          break;
        case 2:
          console.log("Tuesday");
          break;
        case 3:
          console.log("Wednesday");
          break;
        case 4:
          console.log("Thursday");
          break;
        case 5:
          console.log("Friday");
          break;
        case 6:
          console.log("Saturday");
          break;
        default:
          console.log("Sunday");
      }

ln the given code, the dayOfWeek variable is used in a switch statement to identify the corresponding day of the week. Here's how it works:

  • A variable dayOfWeek declared with a value of "4" is assigned to it. This value is then compared to different case statements.

  • The code checks if dayOfWeek is equal to "1" and logs "Monday" into the console if true. The break statement ensures that the switch statement exits once a matching case is found.

  • Similarly, any case from Tuesday to Saturday applies, provided they return true.

  • The default case executes if the value of "dayOfWeek" does not match any case conditions. In this example, "dayOfWeek" is "4", case 4 is true, and "Thursday" is logged to the console.

Switch or If-else statements ? Which should I use?

When it comes to choosing between if-else statements and switch statements, it's a matter of personal preference since both serve similar purposes.

However, if you have if-else statements that evaluate a variable against five or more values, or if you have more than five if-else statements in a block of code, it's recommended to use a switch statement. For instance, in the case of the dayOfWeek example, if we were to write it using if-else statements, we would end up with more than five if-else conditions.

If you prefer using if-else statements in your code, no matter the length, feel free to use them. For practice, try converting our dayOfWeek program from a switch statement to an if-else statement.

Loops

Loops allow for repetitive execution of code. There are three main types of loops:

for loop

for(let i=0; i<5; i++){
   console.log(i)
   // 0
   // 1
   // 2
   // 3
   // 4
}

The for loop is used when the number of iterations is known beforehand. It takes three expressions.

  • The first expression let i = 0 initializes the variable i to zero.

  • The second expression i < 5 states the condition for the code block to run. In this example, the code runs as long as i is less than "5".

  • The code will execute the third expression, increasing i by one, and i will be logged into the console. The code stops running if the second expression is false, which happens when i equals 5.

while loops

The while loop is used when the number of iterations isn't known beforehand. The loop runs provided its specified condition is true.

let count = 0;
while (count < 2){
   console.log(count)
   count++;
    // 0
    // 1
}
  • A count variable is declared in the code above with its value set to "0".

  • The condition in the while loop states that as long as count is less than "0", it is logged into the console and increased the by "1". The output is "0" and "1".

  • Once the value of the count is equal to "2", the condition returns false and the loop is terminated.

do-while loop

The do-while loop is similar to the while loop, with the only difference being that the do-while loop runs at least once before the condition is checked.

let x = 1;
do {
console.log(x);
x++;
} while ( x < 1 )
// output = 1
  • The variable 'x' has been set to the value of one.

  • The value of x is first logged to the console and then incremented by one in the do-while loop.

  • The while loop will continue as long as x is less than 2.

Connecting the Dots

To summarize the article, we will create a simple guessing game. Before we begin writing code, let's break down the problem:

  • The program will prompt the user to select a number between 1 and 10 and provide a response based on the selection.

  • The program will alert a congratulatory message and exit upon a correct guess.

  • The program will prompt the user to input another number for every incorrect choice.

  • The loop will run for five times unless the user chooses to exit.

Now that we understand the challenge, lets begin.

    // generate a random secret number
    let secretNumber = Math.floor(Math.random() * 10) + 1;

    // set value of guess count variable to zero
    let guessCount = 0;

    // declare guess variable without a value
    let guess;

    // while loop allows player to guess up to 5 times
    while (guessCount < 5) {

      // create guess variable that prompts user to input a number or type "quit"
      let guess = prompt("Guess a number between 1 and 10 (or type quit to exit)");

      // if statement whcih exits loop if user inputs "quit"
      if (guess.toLowerCase() === "quit") {
        alert("goodbye");
        break;
      }

      // covert the value of guess input to a number
      guess = parseInt(guess);

      // if statement checking for several conditions by checking if guess is a valid number
      if (!isNaN(guess)) {
        guessCount++;

        if (guess === secretNumber) {
          alert(`Congratulations, you've guessed the number in ${guessCount} tries`);
          break;
        } else if (guess > secretNumber) {
          alert("Too high! Try again")
        } else {
          alert("Wrong! Try again")
        }

      } else {
        alert("Invalid Input. Please enter a number or type quit")
      }
    }

    // game over message
    if (guess !== secretNumber && guessCount === 5) {
      alert(`Sorry, you ran out of guesses! The number was ${secretNumber}`)
    }

Let's break down the code

Setting up

// generate a random secret number
    let secretNumber = Math.floor(Math.random() * 10) + 1;

    // set value of guess count variable to zero
    let guessCount = 0;

    // declare guess variable without a value
    let guess;
  • A number between 1 and 10 is generated using the Math.floor function and kept secret.

  • A variable named guessCount keeps track of the user's guesses.

  • The "guess" variable stores the user input.

Running the while Loop

while (guessCount <5){
    // create guess variable that prompts user to input a number or type "quit"
      let guess = prompt("Guess a number between 1 and 10 (or type quit to exit)");

      // if statement which exits loop if user inputs "quit"
      if (guess.toLowerCase() === "quit") {
        alert("goodbye");
        break;
      }

      // covert the value of guess input to a number
      guess = parseInt(guess);

      // if statement is explained in the next section

}
  • The loop allowing user to guess up to five times is run.

  • The guess variable prompts asks the player to guess a number between 1 and 10 or type "quit" to exit.

  • The following if statement runs if the player types "quit", and ends the game.

  • The player's input is converted to a number using this line of code guess = parseInt(guess), provided the user didn't type "quit".


     // if statement checking for several conditions by checking if guess is a valid number
      if (!isNaN(guess)) {
        guessCount++;

        if (guess === secretNumber) {
          alert(`Congratulations, you've guessed the number in ${guessCount} tries`);
          break;
        } else if (guess > secretNumber) {
          alert("Too high! Try again")
        } else {
          alert("Wrong! Try again")
        }
  • The next if statement checks if the user input is a valid number and increases guessCount by one if true.

  • The next set of if-else statements checks if guess is correct, too high or wrong

  • The nested if statement alerts a congratulatory message, showing the number of tries and exits the game if the player guesses correctly.

} else {
        alert("Invalid Input. Please enter a number or type quit")
      }
  • Program alerts an invalid message if the player enters a value other than a number or "quit".
// game over message
    if (guess !== secretNumber && guessCount === 5) {
      alert(`Sorry, you ran out of guesses! The number was ${secretNumber}`)
    }
  • The program reveals the correct number and ends game if the player's guess is wrong after 5 tries.

To run this code in your local machine, copy the complete code written some sections above (before the "lets break down the code" text), not the explanation that's broken into parts.

Conclusion

Complex applications that solves problems can be built through a strong understanding and application of control flow.

Here's the end of the article. If you found it educative, please share it, like, comment and do let me know.

I appreciate any feedback that will help me write better. Until next time, Happy Coding!