Control flow statements are essential constructs in JavaScript that enable developers to control the flow of program execution based on different conditions.
Using conditional statements and loops, developers can make decisions and execute specific code blocks multiple times. Understanding control flow statements is crucial for writing high-quality and efficient JavaScript code.
This detailed explanation will focus on providing quality information about control flow statements in JavaScript.
Conditional Statements
Conditional statements allow the program to execute code blocks based on certain conditions. JavaScript's most common conditional statements are if
, else if
, and else
.
if Statement
The if
statement executes a block of code if a given condition evaluates to true.
let age = 18;
if (age >= 18) {
console.log('You are an adult.');
}
else if Statement
The else if
statement allows the program to check additional conditions if the initial if condition is false.
let age = 15;
if (age >= 18) {
console.log('You are an adult.');
} else if (age >= 13) {
console.log('You are a teenager.');
} else {
console.log('You are a child.');
}
else Statement
The else
statement provides a fallback block of code to execute when all previous conditions are false.
let day = 'Sunday';
if (day === 'Saturday' || day === 'Sunday') {
console.log('It\'s the weekend!');
} else {
console.log('It\'s a weekday.');
}
Loops
Loops allow the program to execute a code block repeatedly until a specific condition is met. The two main types of loops in JavaScript are for and while.
for Loop
The for
loop is commonly used when the number of iterations is known or can be determined.
for (let i = 1; i <= 5; i++) {
console.log('Iteration:', i);
}
while Loop
The while
loop executes a code block if the specified condition is true.
let count = 1;
while (count <= 5) {
console.log('Count:', count);
count++;
}
switch Statement
The switch
statement provides an alternative to multiple if...else
statements when evaluating a single expression against multiple possible values.
let day = 'Monday';
switch (day) {
case 'Monday':
console.log('It\'s the start of the week.');
break;
case 'Friday':
console.log('It\'s almost the weekend!');
break;
default:
console.log('It\'s a regular day.');
}