Here is the explanation of Control Statements:
JavaScript control statements are used to control the flow of execution in a program.
• They enable you to make decisions, iterate over sequences of data, and execute different code blocks based on certain conditions.
Here are the main types of control statements in JavaScript:
1. Conditional Statements:
- if Statement
if (condition) {
// Code to be executed if the condition is true
}
- if-else Statement
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
- if-else..if-else Statement
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}
- Switch Statement
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// More cases...
default:
// Code to be executed if none of the cases match
}
2. Looping Statements:
- for Loop
for (initialization; condition; iteration) {
// Code to be executed in each iteration
}
- while Loop
while (condition) {
// Code to be executed as long as the condition is true
}
- do-while Loop
do {
// Code to be executed at least once, then repeated as long as the condition is true
} while (condition);
- for…in Loop
for (variable in object) {
// Code to be executed for each property in the object
}
- for…of Loop
for (variable of iterable) {
// Code to be executed for each element in the iterable
}
3. Jump Statements:
- break Statement
Used to terminate a loop or switch statement.
break;
- continue Statement
Skips the rest of the code inside a loop and moves to the next iteration.
continue;
- return Statement
Exits the function and can optionally return a value.
return value;