Table of contents
Control flow is a term used in programming to describe the order in which statements are executed in a program. In JavaScript, control flow refers to the order in which statements are executed based on their logical relationships and conditions.
JavaScript statements are executed sequentially, which means that they are executed in the order in which they appear in the code. However, control flow statements, such as conditional statements and loops, can change the order of execution by controlling which statements are executed and when.
If -else statement
In all programming languages, there is a construct called an if statement. It comprises a condition that is assessed to be true or false and a block of code will be executed based on the condition. When the condition is evaluated to be true, the code within the block executes, otherwise, it's skipped. It's a straightforward concept. Let's examine an example to illustrate this.
if (condition) {
// code to execute if condition is true
}
For example, let's say we want to check if a number is greater than 10. We could use an if statement to do this:
let number = 15;
if (number > 10) {
console.log("The number is greater than 10");
}
In this example, the condition is number > 10, which is true because the number is 15. Therefore, the code inside the curly braces {} is executed, and "The number is greater than 10" is logged to the console.
Now, let's say we want to check multiple conditions. We can use an else if statement to do this. Here's the basic syntax:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
}
For example, let's say we want to check if a number is positive, negative, or zero. We could use an if statement with else if statements to do this:
let number = -5;
if (number > 0) {
console.log("The number is positive");
} else if (number < 0) {
console.log("The number is negative");
} else {
console.log("The number is zero");
}
In this example, the first condition number > 0 is false, so it moves on to the else if statement. The second condition number < 0 is true because the number is -5, so the code inside the second block is executed, and "The number is negative" is logged to the console.
Finally, if we want to execute a block of code if none of the conditions is true, we can use an else statement. Here's the basic syntax:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if neither condition1 nor condition2 is true
}
For example, let's say we want to check if a number is even or odd. We could use an if statement with else statements to do this:
let number = 7;
if (number % 2 === 0) {
console.log("The number is even");
} else {
console.log("The number is odd");
}
In this example, the condition number % 2 === 0 is false because the number is odd. Therefore, the code inside the else block is executed, and "The number is odd" is logged to the console.
Switch Statement
Switch statement is extremely similar to the if statement. They can be used interchangeably, but there are some situations where a switch is preferred. With if statements, you mostly have just a few conditions, one for the if, a few for the if-else, and the final else statement. If you have a larger number of conditions, you might want to consider using the switch statement. Let's explore how it works. The switch statement is used to perform different operations based on different conditions.
Let's say you have a variable superhero, based on the name of the superhero, you want to display his voice line. We can do this by using a switch statement.
Switch statement takes in a value, and then checks it in a bunch of cases:
const superHero = 'Captain America';
switch(superHero){
case 'Iron Man':
console.log('I am Iron Man');
break;
case 'Thor':
console.log('That is my hammer');
break;
case 'Captain America':
console.log('Avengers Assemble');
break;
case 'Black Widow':
console.log('One shot, one kill');
break;
default:
console.log('I not a superHero');
break;
}
//Output: Avengers Assemble
Great, we get exactly what we expected. In this example, we passed the superHero variable to the switch statement. It executes the first check with a triple-equal sign. Since this evaluates to false, it skips it and goes to the next one. As soon as it finds the one that matches correctly, it prints the output.
The break keyword ends the switch when we get the correct case. If we omit the break statement, the next case will be executed even if the condition does not match the case. And finally, what if none of the names in the switch matches the name of our superHero, there must be something like an else statement, right? There is! That something is called default. If none of the cases matches, the default case is going to be executed.
Loops
Loops are used to execute a block of code repeatedly until a certain condition is met. They allow you to automate repetitive tasks and make your code more efficient.
There are several types of loops in JavaScript, including the for loop, while loop, do-while loop, and for...in the loop. Each type of loop is suited for a specific use case, but they all work similarly: they execute a block of code repeatedly until a condition is no longer true
For loops
For loops are used when you know exactly how many times you want to repeat a block of code. Here's the basic syntax of a for loop:
for (initialization; condition; increment/decrement) {
// code to execute
}
Here's what each part of the for loop does:
initialization: This is where you initialize a counter variable before the loop starts. It's usually set to 0 or 1.
conditions: This is the condition that must be true for the loop to continue. It's usually a comparison between the counter variable and some other value, such as a length or a limit.
increment/decrement: This is how the counter variable changes after each iteration of the loop. It can either be incremented (increased by 1) or decremented (decreased by 1).
For example, let's say we want to print the numbers from 1 to 10. We can use a for loop to do this:
for (let i = 1; i <= 10; i++) {
console.log(i);
}
In this example, the counter variable i is initialized to 1. The loop will continue as long as i is less than or equal to 10. After each iteration of the loop, i is incremented by 1. The result is that the numbers from 1 to 10 are printed to the console.
While loops
While loops are used when you don't know exactly how many times you want to repeat a block of code. Here's the basic syntax of a while loop:
while (condition) {
// code to execute
// don't forget to change the condition or you'll create an infinite loop!
}
Here's what the while loop does:
- condition: This is the condition that must be true for the loop to continue. It's usually a comparison between a variable and some other value, such as a length or a limit.
For example, let's say we want to print the numbers from 1 to 10 using a while loop. We can do this by setting a variable i
to 1 and using a while loop to print each number until i is greater than 10:
let i = 1;
while (i <= 10) {
console.log(i);
i++;
}
In this example, the condition i <= 10 is true as long as i is less than or equal to 10. After each iteration of the loop, i is incremented by 1. The result is that the numbers from 1 to 10 are printed to the console.
It's important to be careful when using loops to avoid creating infinite loops, which can cause your program to crash or freeze. Make sure the condition will eventually become false, or use a break statement to exit the loop early if necessary.