JavaScript Control Flow

JavaScript Control Flow

As you begin to write complex programs, there will be a point in your code where you need to make some kind of a decision on what to do next, or perhaps execute a piece of code over and over, you will want to be able to control the flow of your code.

For example, if you have an array of data, perhaps an array of names that you want to circle through and perform some code on each element inside the array, then you will have to use a loop. Loop is a type of control Flow in Javascript.

Likewise, you may want to check if a certain condition is met (perhaps if a user is logged in or not) and execute a code when a defined condition is met. This is referred to as conditional statements or IF statements.

Both the looping and conditional statement concepts are collectively known as control flow in JavaScript because we use them to control the flow of our code or application whether it is using loop to repeat a particular session of code or to run a session of code based on certain condition(s).

In this article, we will be taking a look at these concepts, and try to understand their effect on our work and the impact they can have on our coding decision.

Loops

First, let's start with loops and one in particular which is the for loop. There are different types of loops in JavaScript, and we going to discuss them one after the other.

For Loops

The syntax of the for loop is easy to grasp. The syntax is for( let i = 0; i < 7; i++){...}.

Note: in loops, we don't add a semicolon at the end of the curly braces, if we did it would have looked like this for( let i = 0; i < 7; i++){...}; .

Remember the job of a loop is to go over a piece or session of code repeatedly a certain number of times.

Now from the loop syntax we wrote above; the opening and closing curly brackets are often referred to as code blocks. A code block as seen in the syntax above is a session of code that we session off for the loop.

The for loop is created by first saying the for keyword and then we add some parenthesis. The parenthesis contains three different things. The first thing is the Initializer variable let i = 0;, by initializing this variable, we are actually saying we want to create a variable i and assign the value zero (0) to it. The variable is more or less like a counter and it keeps count of how many times we circle through the loop and how many times we run the code inside it.

The second thing is the condition i < 7; which is going to evaluate either true or false. If the Condition is true then we will execute the code block, but if it is false then we won't run the code.

The third thing is the final expression i++ which is going to execute every time at the end of the code block. Every time we loop through some code, at the end we are going to take i and add 1 to it.

 for(let i = 0; i < 5; i++){

 }

In our loop, we set i = 0 , then we check our condition, is i less than 5? Yes it is because it is currently 0 , then we execute some kind of code inside the code block. when we have executed that code, we come back to the i++ expression, we take i which is currently 0 and we add 1 to it. Then go over to the beginning, but this time we don't reinitialize the variable again, we just keep i as 1 because we are just adding one to it. then we recheck the condition, is i still less than 5? yes it is, because it is still 1, then we execute the code block again and at the end, we do the final expression again, we add 1 to i it becomes 2. Then we go to the beginning again, is 2 less than 5? yes, it is, we go over the same process and loop through over and over until i is equal to five and then we don't loop through the code again because we have completed our code based on the condition we set.

Let's see it in action

 for(let i = 0; i < 5; i++){

   console.log('in loop', i)
 }

  console.log('loop finished')

From the above code we console logged ('in loop, i ) which is the code we want to run within our code block. By doing this we are trying to loop through i and output our result on the console, if we do that, the output will look like this:

We won't see five because at the point where i is equal to 5, it's not less than five anymore and it does not execute the code in our code block anymore.

Often times in real-world situations we may not know how many times we want to loop through something. typically what we do is loop through data of some kind. It could be a list of users or names from a database, and we do not know how many people are in that list or array of names, but we want to circle through them and perform a for loop for each name in the array and do something with them.

In other to show this, let's create an array of cars and circle through them.

The codes below explain:

const cars = ['Toyota', 'Honda', 'Benz', 'Ford']

 for(let i = 0; i < cars.lenght; i++){

   console.log(cars[i])
 }

From the code above, we are looping through an array of cars, remember, normally if we were fetching this data from a database we may not likely know the number of items in the array of cars, but in our case, we know it because we wrote it, but let's just pretend we don't know what number of items is contained in the array of cars so we can easily understand the concept.

In the for loop we initialized a variable and set it to zero (let i = 0; ) which is our counter, then we said for i less than cars.length; what this does is that it's going to take the length of cars which is 4 and it's going to say for as long as i is less than 4 circle through it. Then finally the incremental expression i++.

Inside the curly braces, we logged in the car that we circle over each time and added i inside of a square bracket notation because if we don't do it that way and just log it directly inside of parenthesis we won't get the cars but numbers instead.

It will look like this:

const cars = ['Toyota', 'Honda', 'Benz', 'Ford']

for(let i = 0; i < cars.length; i++){

  console.log(i)
}

This will be the output:

The above output is not what we want which is why we added i inside a square bracket [ i ].

Now the output of our code with the square bracket notation will look like this:

We circled through the array of cars using the cars.length which is what we do when we want to circle through an array of an unknown length, it does not matter the length we can circle through it using the .length property.

While Loop

The while loop is similar to the for loop with just some syntax differences (how we write it).

 let i = 0;

while(i < 5){

  console.log('loop in',i);

  i++;
}

From the above code, the first thing we did was change the for keyword to while. In the while loop, we don't have all three statements inside the parenthesis. rather we only have one of them inside the parenthesis and that is the condition i < 5 ; so we are saying while i is less than five, run the code inside of our code block. then we declared our variable outside of the loop. Lastly, we have our incremental expression i++ inside of the code block. if we output this code it will look the same as the output we had for the for loop.

Do While Loop

The do while loop is just an extension of the while loop.

In the while loop, we evaluate a condition and if it is true we run a particular defined code. Now imagine we start off by setting our variable to let i = 5.

Our condition i < 5 is never going to be true, and our code will never run. although that might be fine, at least you want the code to run once even if the condition i < 5 is not true. To do this we use the do while loop.

 let i = 5;

 do{

  console.log('the value of i is',i);

  i++;
} while(i < 5);

The above output is what we will have when we run the code, this is so because we ran it once and i is 5.

Remember we don't add the semi-colon to loops. The semi-colon in the while statement is only there because it is a "while statement".

Conditional/If Statement

The if statement is another form of control flow in Javascript; it is called an " if statement" because we check if a certain condition is true, then we do something.

With the if statement we don't use any form of counter variables because we only execute the condition ones or not at all. We don't circle through the whole code multiple times as we did in loops.

Let's look at some examples.

const age = 25

 if( age > 25){

   console.log('you are over 25')

 }

From the code above we declared a variable age and set it to 25, and we did a conditional check, an (If statement), then in the parenthesis we did a check; we said "if" age is over 25, in our code block ( where we want to do something), we logged "you are over 25". This code will only return if the condition is true. based on what we have in our code currently if you preview it on your console, you will not see anything and that is because the condition is not true(age is not over 25, age is equal to 25) but if we change age to 30, it will evaluate to true and when we preview will see what we logged to the console.

The code will look like this:

const age = 30

 if( age < 25){

    console.log('you are over 25')

 }

Based on the code above our output on the console will be:

Now on our console, we have the string "you are over 25".

We can also do an if statement with data to check if we have a certain amount of items in an array. but beyond that, there are many other things we can do with the if statement like check if a user's sign-up or log-in details are correct or not.

Let's take an example:

const passWord = "done"

 if(passWord.length >= 8){

  console.log('password is okay')
};

In the code above we first declared a variable password and set it to a string "done" which is 4 in number(d.o.n.e), then we wrote a condition to check if at least the password is eight characters long or greater than that, then we logged on our console 'password is okay'. at this point, if we check our console, we won't see anything because the password is not at least eight characters long. But if we go ahead to change the password value like the code below.

const passWord = "done23344"

 if(passWord.length >= 8){

  console.log('password is okay')
};

By changing the password from 'done' to 'done23344' our code will run because the condition will execute to true. and our output will be like this:

Sometimes we may want feedback on some information if the first code does not execute. If the password was still 'done' and we don't want our console to be empty as it was initially, we might want to tell the user that the password is not good enough instead of just leaving it empty.

This is where the else statement comes in.


const passWord = "done"

 if(passWord.length >= 8){

  console.log('password is okay')
}else{
    console.log('password is not good enough')
}

We modified our code and added the else statement. At this point the console will no longer be empty, it will display the code in the else statement code block because the first condition is not true. Notice that it is only going to run one of these code blocks, either the if or else, never both of them.

There are also times when we might want to check multiple conditions. for example, we may want to check if the password is twelve characters long if it is, we might want to output "this password is very good ", if it's not, then we will do another check, is the password at least eight characters long? if it is. then we will output 'password is okay" otherwise, we will output "password is not good enough".

Let's explain how this can be done with the code below:


const passWord = "done"

 if(passWord.length >= 12){

  console.log('this password is very good')
} else if(passWord.length >= 8){

    console.log('password is okay')
}else{
    console.log('password is not good enough')
}

The code above can only ever run one of the conditions. The only difference in this code is the introduction of the esle if statement. we are generally saying that we want our code to run the first code block if the condition is met, otherwise run the second condition but in a situation where neither the first nor second is met run the third. you can play around with it on your console and see how the output changes when the password length changes.

Logical Operators OR || and AND &&

As we keep building programs, there might be times when we want to satisfy a combination of different conditions all at once inside the same check. what we've done so far is that we've been checking just one condition inside a parenthesis. Checking a combination of conditions inside a parenthesis is more or less like saying: if(boy and girl){}. The boy is the first condition and the girl is the second(we are just saying check for boy and girl before you run our code block). it can also be if (boy or girl){}.

This concept is known as logical operators: the logical OR || which looks like two pipes, and the logical AND && which looks like two ampersands.

Example

Imagine a situation where we want to add the @ symbol in our condition before the first code block runs. that is; the password must include an @ symbol before the code runs. Doing that our code will look like this:


// code 1
const passWord = "done11223344"

 if(passWord.length >= 12 && passWord.includes('@') ){

 console.log('this password is very good')

} else if(passWord.length >= 8 || password.includes('@'){

    console.log('password is okay')
}else{
    console.log('password is not good enough')

//code 2
const passWord = "done@11223344"

 if(passWord.length >= 12 && passWord.includes('@') ){

 console.log('this password is very good')

} else if((passWord.length >= 8 || password.includes('@')){

    console.log('password is okay')
}else{
    console.log('password is not good enough')

In the above code, we added the @ symbol using the .includes() method because we want the two conditions to be true. For the code to run the password must be at least twelve characters long and must also include an @ symbol. the two conditions must be true before the code can run. If you run code 1 and preview on the console, it will ignore the first code block and run the second which is 'password is okay' this is because the password does not include the @ symbol. On the other hand, if you run code 2 and preview on the console, the first code block will execute because the two conditions are true.

That is for using the logical AND operator &&. Now, let's look at the OR ||

// code 1
const passWord = "done@"

 if(passWord.length >= 12 && passWord.includes('@') ){

 console.log('this password is very good')

} else if((passWord.length >= 8 || password.includes('@')){

    console.log('password is okay')
}else{
    console.log('password is not good enough')

//code 2
const passWord = "done1122"

 if(passWord.length >= 12 && passWord.includes('@') ){

 console.log('this password is very good')

} else if((passWord.length >= 8 || password.includes('@')){

    console.log('password is okay')
}else{
    console.log('password is not good enough')

In our code the else if code block will run if one of the conditions is true. So even if the password is four 0r five characters as long as it includes the @ symbol as in code 1, the code will still run. When we use the OR || operator only one condition has to be true. if we have the password as the one in code 2, the code will still run because it is at least eight characters long.

Switch Statements

The switch statement is another type of control flow in javascript. the switch statement is similar to the if statement, in fact, they do basically the same thing. But the switch statement comes to the rescue when we have a program that requires a lot of checks. Using the if statement can sometimes get messy to read compared to the switch statement.

Example


   const color = 'red'

   switch (color) {

    case 'white':
        console.log('the color is white')
        break;

    case 'pink':
        console.log('the color is pink')
        break;

    case 'blue':
        console.log('the color is blue')
        break;

    case 'red':
        console.log('the color is red')
        break;

    default:
       console.log('the color does not exist')

   }

In the above code, we declared a variable color and set its initial value to red, then we wrote a switch statement starting with the switch keyword and set our key which is the color in the parenthesis.

Then we opened our code block, and inside our code block, we have different cases. What this means is that; if the color variable is set to any of the cases, the code of that case which in our case is the console.log should run.

Currently, color is set to red, now if you preview on your console what you would see is " the color is red".

Then we have the default case, which uses the default keyword. In any case, where none of the cases matches the color variable, the default case which is "the color does not exist" will run".

Now you've learned JavaScript controle flow. keep practicing and with time you get better at using them. Happy Coding.

fjjjjjjjjjjjjhhgfkjyjuyiui