Control flow statements are used to control the flow of execution in a program. They are used to make decisions, execute loops, and handle errors. There are three types of control flow statement in JavaScript:
- Conditional Statements
- Loops
- try/catch statements.
Conditional Statements:
Conditional statement in JavaScript are used to make decisions based on certain conditions. These allow you to execute different blocks of code depending on whether a given condition evaluates to true or false. The main types of conditional statements in JavaScript are:
1. if statements:
The if statement is used to execute a block of code if a specified condition is true.
let age = 18;
if(age >= 18) {
console.log('You are an adult.');
}
2. if-else statement:
The if-else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false.
let temperature = 25;
if(temperature > 30){
console.log("It's hot outside.")
} else {
console.log({"It's not too hot.");
}
3. if-else if-else statement:
This allows you to check multiple condition in a sequence and execute the block of code corresponding to the first true condition.
let time = 14;
if(time < 12){
console.log('Good morning');
} else if(time < 18) {
console.log('Good afternoon!');
} else {
console.log('Good evening!');
}
Loops
Loops are used to repeatedly execute a block of code as long as specified condition is true.
There are mainly two types of loops in JavaScript.
1. For loop:
The for loop allows you to execute a block of code repeatedly for a specific number of iterationd.
for(let i = 1; i <= 5; i++){
console.log('Iteration '+i)
};
2. while loop:
The ‘while‘ loop repeatedly executes a block of code as long as a specific condition is true/
let count = 0;
while (count < 5) {
console.log("Count: "+ count);
count++;
}
try/catch Statements:
The try/catch statement is used for error handling in JavaScript. It allows you ti catch and handle errors that might occur during the execution of a block of code.
try {
// Code that might throw an error
let result = 10/0;
console.log(result);
} catch (error) {
console.log('An error occurred: '+error);
}
Break and Continue
They allow you to alter the execution of a loop on certain conditions.