JavaScript PART 4: CONTROL FLOW STATEMENTS IN JavaScript
Please Subscribe Youtube| Like Facebook | Follow Twitter
Control Flow Statements In JavaScript
In this article, we will provide a detailed overview of control flow statements in JavaScript and provide examples of how they are used in JavaScript programming.
Control flow statements are an essential part of programming languages like JavaScript. These statements allow programmers to execute specific sections of code based on certain conditions or repeatedly execute the same code multiple times. In this article, we will explore the different control flow statements in JavaScript, including if/else statements, switch statements, for loops, while loops, and do-while loops.
If-else statement
If/else statements are conditional statements that allow us to execute a block of code if a condition is true, and another block of code if the condition is false. The syntax of an if/else statement is as follows:
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
In an if-else statement, the code inside the first set of curly braces is executed if the condition is true. If the condition is false, the code inside the second set of curly braces is executed.
In some cases, you may need to evaluate multiple conditions. In these cases, you can use the else if statement. Here is the syntax for multiple if-else statement:
if (condition1) { // code to be executed if condition1 is true } elseif (condition2) { // code to be executed if condition2 is true } else { // code to be executed if all conditions are false }
The else if statement allows you to evaluate multiple conditions and execute different blocks of code based on the result of the evaluations.
Here’s an example of if-else statement in JavaScript
let age = 16;
if (age < 18) {
console.log("You are too young to vote.");
} else if (age >= 18 && age < 65) {
console.log("You can vote.");
} else {
console.log("You can retire and enjoy life.");
}
Output
You are too young to vote.
In this example, we declare a variable age and assign it a value of 16. We then use multiple if-else statements to check the value of age and output different messages depending on the value.
The first if statement checks if age is less than 18. If it is, the message “You are too young to vote.” is logged to the console.
If the first condition is false, the second if statement checks if age is greater than or equal to 18 AND less than 65. If it is, the message “You can vote.” is logged to the console.
Finally, if all the above conditions are false, the else statement is executed, which logs the message “You can retire and enjoy life.” to the console.
In our case, age is 16, which satisfies the condition in the first if statement, so the message “You are too young to vote.” is logged to the console.
Switch Statement
Switch statements are another type of conditional statement that allow us to execute different blocks of code based on the value of a variable. The syntax of a switch statement is as follows:
switch (expression) { case value1: // code to be executed if expression matches value1 break; case value2: // code to be executed if expression matches value2 break; ... default: // code to be executed if none of the cases match break; }
expression: The expression whose value is compared to each case clause.
case: A keyword followed by a value to be compared to the expression.
break: A keyword that stops the execution of the switch statement.
default: A keyword that specifies code to be executed if none of the cases match the expression.
When a switch statement is executed, the value of the expression is compared to each of the values specified in the case clauses. If a match is found, the code block associated with that case is executed. If no match is found, the code block associated with the default clause is executed (if present). The break keyword is used to exit the switch statement and prevent the execution of subsequent cases.
Here’s an example of Switch statement in JavaScript
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday");
break;
case "Tuesday":
console.log("Today is Tuesday");
break;
case "Wednesday":
console.log("Today is Wednesday");
break;
default:
console.log("Today is some other day");
break;
}
Output
Today is Monday
The above code is an example of the switch statement in JavaScript.
We define a variable day and assign it a value of “Monday”. We then use a switch statement to compare the value of day to each case clause. Since day is equal to “Monday”, the code block associated with the case “Monday” clause is executed, which outputs the string “Today is Monday” to the console. The break keyword is used to exit the switch statement and prevent the execution of subsequent cases.
For loop
For loops are used to execute a block of code a specific number of times. The syntax of a for loop is as follows:
for (initialization; condition; increment/decrement) { // code to be executed }
The initialization statement is executed before the loop starts and is used to initialize the loop variable(s). This statement can declare new variables or assign values to existing variables.
The condition statement is evaluated before each iteration of the loop. If the condition evaluates to true, the loop continues to execute. If it evaluates to false, the loop terminates.
The increment/decrement statement is executed at the end of each iteration of the loop. This statement is used to modify the value of the loop variable(s) in order to eventually cause the condition to evaluate to false and terminate the loop.
The code block enclosed in curly braces {} contains the statements that are executed for each iteration of the loop. This is the code that performs the actual work of the loop.
Here’s an example of For loop in JavaScript
for (let i = 0; i < 5; i++) {
console.log("The value of i is " + i);
}
Output
The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4
This for loop iterates from 0 to 4, incrementing the i variable by 1 on each iteration. Inside the loop, the value of i is printed to the console using string concatenation with the message “The value of i is “.
Break and Continue Statements Inside a For Loop
In JavaScript, the break and continue statements can be used inside for loops to control the flow of the loop. Here’s a brief explanation of each:
break: When break is encountered inside a for loop, it immediately terminates the loop and control passes to the statement following the loop.
continue: When continue is encountered inside a for loop, the loop skips the remaining statements in the current iteration and moves on to the next iteration.
Here’s an example that shows the use of break and continue inside a for loop:
for (var i = 1; i <= 10; i++) {
if (i === 5) {
// terminate the loop early
break;
} else if (i === 3) {
// skip this iteration
continue;
}
console.log(i);
}
Output
1 2 4
In this example, the loop iterates from 1 to 10, but when i is 5, the break statement is encountered and the loop is terminated early. When i is 3, the continue statement is encountered and the loop skips the remaining statements in that iteration before moving on to the next iteration.
Note that break and continue can also be used inside other types of loops, such as while and do-while loops.
While loop
While loops are used to execute a block of code as long as a certain condition is true. The syntax of a while loop is as follows:
while (condition) { // code to be executed }
The condition statement is evaluated before each iteration of the loop. If the condition evaluates to true, the loop continues to execute. If it evaluates to false, the loop terminates.
The code block enclosed in curly braces {} contains the statements that are executed for each iteration of the loop. This is the code that performs the actual work of the loop.
Here’s an example of While loop in JavaScript
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output
1 2 3 4 5
The while loop in this example initializes a variable i to a value of 1, then checks if i is less than or equal to 5. If the condition is true, the loop prints the current value of i to the console and increments i by 1. The loop then checks the condition again, and repeats until i is no longer less than or equal to 5.
Do-while loop
Do-while loops are similar to while loops, but the code inside the loop is executed at least once, even if the condition is initially false.
The key difference between a do-while loop and a while loop is that the do-while loop will always execute the code inside the loop at least once, even if the condition is false initially. This can be useful in situations where you need to perform an action at least once, regardless of the condition.
The syntax of a do-while loop is as follows:
do { // code to be executed } while (condition);
do: This keyword is used to indicate the start of the do…while loop.
{}: This pair of curly braces is used to enclose the code block that will be executed as part of the loop.
// code to be executed: This is the code that will be executed in each iteration of the loop.
while: This keyword is used to specify the condition that will be checked after the code block has been executed. If the condition is true, the loop will execute again.
(condition): This is the condition that will be evaluated after the code block has been executed. If the condition is true, the loop will execute again.
Here’s an example of Do-while loop in JavaScript
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Output
1 2 3 4 5
This loop starts by initializing the variable i to 1. Then, the code block is executed, which logs the value of i to the console and increments i by 1. After the code block is executed, the condition i <= 5 is checked. Since the value of i is now 2 and the condition is true, the loop executes again.
This process continues until the value of i is 6. At that point, the condition i <= 5 is false, and the loop exits.
Conclusion
In conclusion, control flow statements in JavaScript are essential for creating programs that execute specific instructions under various conditions. Understanding the different types of control flow statements available, such as if-else statements, switch statements, for loops, while loops, and do-while loops, is crucial for any developer looking to write efficient and effective code. With these tools at their disposal, developers can create programs that are more dynamic and responsive to user input.
JavaScript Beginner Tutorial Series
- JavaScript Part 1: Setup and Introduction
- JAVASCRIPT PART 2: Understanding Basic Data Types And Variables In JavaScript
- JavaScript PART 3: OPERATORS AND EXPRESSIONS IN JavaScript
- JavaScript PART 4: CONTROL FLOW STATEMENTS IN JavaScript
- JavaScript PART 5: FUNCTIONS IN JavaScript
- JavaScript Part 6: Arrays In JavaScript
- JavaScript Part 7: String Manipulation In JavaScript
- JavaScript Part 8: Object-Oriented Programming In JavaScript (Classes and Objects)
- JavaScript Part 9: Object-oriented Programming In JavaScript (OOP Pillars)
- JavaScript Part 10: Exception Handling in JavaScript