JavaScript Conditional and Loop Control Statements
JavaScript Conditional and Loop Control Statements
JavaScript Conditional and Loop Control Statements
1. CONDITIONAL STATEMENTS
Definition: Conditional statements are used to make decisions in code. They allow execution of different code blocks
based on true/false conditions.
1.1 if Statement
- Executes a block of code if the condition is true.
Syntax:
if (condition) {
// code to execute
1.2 if...else Statement
- Executes one block if true, another if false.
Syntax:
if (condition) {
// if block
} else {
// else block
1.3 if...else if...else Statement
- Checks multiple conditions in sequence.
Syntax:
if (cond1) {
} else if (cond2) {
} else {
}
JavaScript Conditional and Loop Control Statements
1.4 switch Statement
- Used for fixed value comparisons.
Syntax:
switch(expression) {
case val1: break;
case val2: break;
default:
1.5 Ternary Operator
- Shorthand for if...else.
Syntax: condition ? value1 : value2;
2. LOOP CONTROL STATEMENTS
Definition: Loop statements allow repeating a block of code multiple times based on a condition.
2.1 for Loop
- Used when iteration count is known.
Syntax:
for (init; condition; increment) {
// code
2.2 while Loop
- Runs as long as the condition is true.
Syntax:
init;
while(condition) {
// code
increment;
JavaScript Conditional and Loop Control Statements
2.3 do...while Loop
- Executes at least once.
Syntax:
init;
do {
// code
increment;
} while(condition);
2.4 for...in Loop
- Iterates over object properties.
Syntax:
for (key in object) {
// code
2.5 for...of Loop
- Iterates over iterable values.
Syntax:
for (value of iterable) {
// code
3. LOOP CONTROL STATEMENTS
3.1 break Statement
- Exits the loop immediately.
3.2 continue Statement
JavaScript Conditional and Loop Control Statements
- Skips the current iteration.
Summary Table
| Statement | Use Case |
|--------------|--------------------------|
| if | Check conditions |
| switch | Fixed value comparisons |
| for | Known iteration count |
| while | Unknown count |
| do...while | At least one iteration |
| break | Exit loop early |
| continue | Skip iteration |