Conditional Statements and Loops
🎯 Introduction
Control flow statements are key to handling program logic in JavaScript. Conditional statements let programs choose different actions depending on the situation; loops repeat operations, improving efficiency and code reuse.
This article explains common structures such as if, switch, for, and while, along with break and continue for controlling loops. These tools help you write more flexible front-end code.
🔄 What Is Control Flow?
Control flow statements determine the order in which code runs and how often it runs. Instead of executing every line sequentially, a program can choose a branch or repeat a block of code.
Put simply:
- Conditionals make choices: statements such as if and switch select a branch based on a condition or value.
- Loops repeat work: statements such as for and while perform the same operation multiple times.
Control flow gives a program the ability to adapt its behavior to different situations.
🛠️ if Statements: Making Choices in Code
if is the most common conditional statement. Its syntax is straightforward:
if (condition) {
// Code to run when the condition is true
} else {
// Code to run when the condition is false (optional)
}
For example:
var age = 20;
if (age >= 18) {
alert('You are an adult');
} else {
alert('You are a minor');
}
This checks the age and displays “You are an adult” if the condition is met, or “You are a minor” otherwise.
Use else if to check additional conditions:
var score = 75;
if (score >= 90) {
alert('Excellent');
} else if (score >= 60) {
alert('Pass');
} else {
alert('Fail');
}
This displays a different assessment for each score range.
🔀 switch Statements: Choosing Among Several Cases
When an if...else chain has many branches, switch can be clearer. It matches an expression’s value against different case clauses:
var fruit = 'apple';
switch (fruit) {
case 'apple':
alert('This is an apple');
break;
case 'banana':
alert('This is a banana');
break;
default:
alert('Unknown fruit');
}
Here, switch checks fruit and runs the matching case. break exits the switch statement, preventing execution from continuing into later cases.
🔁 for Loops: Repeating an Operation
for is a commonly used loop structure. Its syntax is:
for (initialization; condition; update) {
// Loop body
}
For example, to print the numbers 1 through 5:
for (var i = 1; i <= 5; i++) {
console.log(i);
}
Execution proceeds as follows:
- Initialize: i = 1
- Test the condition: i <= 5; if true, run the loop body
- Execute console.log(i) in the loop body
- Evaluate the update expression: i++
- Repeat steps 2–4 until the condition is false, then exit the loop
🔄 while Loops: Continue While a Condition Holds
A while loop tests a condition to decide whether to continue. It is useful when the number of iterations is not known in advance.
Syntax:
while (condition) {
// Loop body
}
For example:
var n = 1;
while (n <= 5) {
console.log(n);
n = n + 1;
}
While n is less than or equal to 5, this code prints n and increases it by 1 after each iteration.
🚦 break and continue: Controlling Loops
- break exits a loop early, for example when a particular condition is met.
for (var i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit when i reaches 5
}
console.log(i);
}
// Output: 1 2 3 4
- continue skips the rest of the current iteration and proceeds to the next one.
for (var i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the remaining code when i is 3
}
console.log(i);
}
// Output: 1 2 4 5
These keywords give you finer control over loop execution.
❓ Knowledge Check
Q1: How do if and switch differ?
if works well for complex conditions and ranges. switch is clearer when comparing a variable against several fixed values. Use break to prevent unwanted fall-through between cases.
Q2: How do for and while loops differ?
for groups initialization, condition, and update on one line and suits a known number of iterations. while specifies only a condition and suits situations where the number of iterations is unknown.
Q3: Why use break and continue?
break ends a loop early to avoid unnecessary iterations. continue skips the rest of the current iteration and proceeds to the next one, avoiding unnecessary work.
🧪 Exercises
Exercise 1: Classify a Score
Check the score variable and output the appropriate grade:
- For a score of 90 or above, output “Excellent”
- Otherwise, for a score of 60 or above, output “Pass”
- Otherwise, output “Fail”
<script>
var score = 85;
// Write your code here
</script>
Exercise 2: Print Even Numbers
Use a for loop to print all even numbers from 1 through 10.
for (var i = 1; i <= 10; i++) {
// Write your code here
}
🎉 You now know how to use if, switch, for, while, break, and continue to control program flow. These foundations help you write more flexible front-end programs. Keep practicing!
