Controlling the Flow — Conditions and Loops in JavaScript
Control flow is the beating heart of every JavaScript program. It decides what runs, when it runs, how many times it runs, and under which conditions it should stop. Without mastering conditions and loops in JavaScript, you can write code, but you cannot truly control it.
In this guide, you will learn how to use if-else statements, the switch statement, and all the core JavaScript loops (for, while, do-while, and for…of). Along the way, you will see clean, practical examples and patterns you can apply directly in real-world projects.
What Is Control Flow in JavaScript?
Control flow describes the order in which JavaScript executes statements in your code. By default, JavaScript runs from top to bottom, line by line.
Conditions and loops allow you to bend that straight line. You can:
- Skip certain blocks of code
- Run different branches based on data
- Repeat a block of code until a condition changes
- Break out of or continue within loops for fine-grained control
Once you grasp these tools, you can move from simple scripts to robust logic like validation flows, menu navigation, and data processing pipelines. You will also be ready for more advanced concepts like asynchronous JavaScript and functional patterns, which rely heavily on predictable control flow.
Using Conditions in JavaScript: if, else if, else
Conditional statements in JavaScript decide which code block should run based on a Boolean expression. The workhorse here is the if-else structure.
Basic if Statement
Use an if statement when you want to run code only if a condition is true.
const age = 20;
if (age >= 18) {
console.log("You can enter.");
}
If the condition evaluates to true, the block runs. If not, it is skipped.
If-Else: Either This or That
Use if-else when you must choose exactly one of two paths.
const isLoggedIn = false;
if (isLoggedIn) {
console.log("Show dashboard.");
} else {
console.log("Redirect to login page.");
}
Here, either the dashboard is shown, or the user is redirected. There is no third outcome.
Else If: Multiple Conditions in a Sequence
When you have more than two cases, chain them with else if.
const score = 72;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else if (score >= 60) {
console.log("Grade C");
} else {
console.log("Grade D");
}
JavaScript evaluates each condition from top to bottom and runs the first matching block. Once a block matches, the rest are skipped, so order matters.
Common Patterns with if-else Conditions
- Guard clauses: check for invalid or edge cases early and return, keeping the main logic simpler.
- Range checks: ideal for validation (age, score, price ranges).
- Feature toggles: enable or disable functionality based on flags.
As your JavaScript codebase grows, consider extracting complex conditions into descriptive functions like isEligibleForDiscount(user) to keep your flow readable.
The switch Statement: Cleaner Multi-Branch Control
When your conditions compare the same value against many different options, a switch statement can be clearer than a long else if chain.
Basic switch Example
const day = "Tue";
switch (day) {
case "Mon":
console.log("Start of the week");
break;
case "Tue":
case "Wed":
case "Thu":
console.log("Midweek grind");
break;
case "Fri":
console.log("Almost weekend");
break;
case "Sat":
case "Sun":
console.log("Weekend!");
break;
default:
console.log("Unknown day");
}
Key points about switch in JavaScript:
- Use
breakto stop execution after a case; otherwise, execution “falls through” to the next case. - You can stack cases (as with
Tue,Wed,Thu) when they share the same behavior. defaultruns when no other case matches, similar toelse.
Use switch for things like navigation based on route names, command handling in CLIs, or mode-based logic. In a larger application (for example, in a separate routing or configuration module you might build later), switch keeps related paths grouped in one place.
Loops in JavaScript: Repeating Actions with Control
Loops let you repeat a block of code multiple times. This is essential when processing arrays, generating UI elements, or running retry logic. JavaScript offers several loop types, each suited to different patterns.
The Classic for Loop
The for loop is the most customizable and is excellent when you know exactly how many iterations you need.
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}
The for loop has three parts:
- Initialization:
let i = 0; - Condition:
i < 5;(loop runs while this is true) - Final expression:
i++;(runs after each iteration)
Use a for loop when you need index access (e.g., you want both the array index and the value). In many codebases, you will still see this style for operations that depend on positions.
While Loop: Repeat Until a Condition Changes
A while loop runs as long as its condition remains true. It is useful when you do not know in advance how many times you need to iterate.
let counter = 3;
while (counter > 0) {
console.log("Countdown:", counter);
counter--;
}
Here, the code continues while counter > 0. Be careful: if the condition never becomes false, you create an infinite loop, which can freeze the browser or node process.
Do-While Loop: Run at Least Once
The do-while loop guarantees the body runs at least one time before checking the condition.
let attempts = 0;
let success = false;
do {
attempts++;
console.log("Attempt", attempts);
// simulate a condition that might become true
if (attempts === 3) success = true;
} while (!success && attempts < 5);
This pattern is helpful for user input prompts or retry logic where the first attempt should always occur.
for…of Loop: Clean Iteration Over Iterables
The for…of loop is a modern, readable way to iterate over arrays, strings, and other iterables when you care about values, not indexes.
const fruits = ["apple", "banana", "mango"];
for (const fruit of fruits) {
console.log(fruit.toUpperCase());
}
Compared with the classic for loop, for...of is easier to read and less error-prone when you only need each item itself. Many style guides now recommend it as the default for array iteration.
for…in Loop: For Object Keys (Use with Care)
The for…in loop iterates over the enumerable properties of an object. It is most commonly used for plain objects, not arrays.
const user = {
name: "Asha",
age: 25,
role: "admin"
};
for (const key in user) {
console.log(key, ":", user[key]);
}
Avoid for...in with arrays because it iterates over keys (which can include inherited properties) rather than only numeric indexes. For arrays, for, for...of, or higher-order methods like forEach are more predictable.
Controlling Loops with break and continue
Inside any loop, you can refine control flow even more using break and continue.
Using break to Exit a Loop Early
break stops the loop immediately and jumps to the first line after the loop.
const numbers = [3, 7, 12, 5, 9];
for (const n of numbers) {
if (n > 10) {
console.log("Found big number:", n);
break; // stop searching
}
}
Use break when you do not need further iterations once a condition is satisfied, such as finding the first match in a search.
Using continue to Skip to the Next Iteration
continue skips the rest of the current loop body and proceeds with the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skip 3
}
console.log("Value:", i);
}
Here, all values from 1 to 5 are logged except 3. This is useful when you want to ignore certain cases without exiting the loop entirely.
Writing Clean, Readable Control Flow
As you start combining conditions and loops in JavaScript, it is easy for the logic to become tangled. Following a few guidelines keeps your control flow clean and maintainable.
Avoid Deeply Nested if-else Blocks
Too many nested conditions are hard to reason about. Instead:
- Use early returns to exit functions on error or edge cases.
- Split logic into smaller helper functions like
hasAccess(user)orgetDiscountRate(cart). - Replace long chains of
if-elsewithswitchor lookup objects when appropriate.
Prefer Descriptive Conditions
Instead of writing complex expressions inline, extract them into clearly named variables or functions. For example:
// Hard to scan
if (user.age >= 18 && user.isVerified && !user.isBanned) {
// ...
}
// Easier to read
const canAccess = user.age >= 18 && user.isVerified && !user.isBanned;
if (canAccess) {
// ...
}
This approach also makes it easier to reuse the same control logic across different modules or components in your application (for example, on both the client and server side).
Use the Right Loop for the Job
- for: when you need indexes or a specific iteration pattern.
- for…of: when you just need values from an array or iterable.
- while: when the number of iterations is unknown and depends on a changing condition.
- do-while: when you must run at least once before checking.
- for…in: when iterating over object keys.
Putting It All Together: Example Flow in JavaScript
Here is a small, realistic example that combines conditions and loops in JavaScript to process a list of users and categorize them.
const users = [
{ name: "Ravi", age: 17 },
{ name: "Maya", age: 22 },
{ name: "Ali", age: 19 },
{ name: "Kiran", age: 15 }
];
for (const user of users) {
if (user.age < 16) {
console.log(user.name + " is too young for the survey.");
continue; // skip the rest of the loop for this user
}
let category;
if (user.age < 18) {
category = "teen";
} else if (user.age < 25) {
category = "young adult";
} else {
category = "adult";
}
console.log(user.name + " is a " + category + ".");
}
This compact snippet showcases:
- Looping through an array with
for...of - Skipping certain items with
continue - Using conditional logic to assign categories
Patterns like this appear throughout real applications, from filtering product lists to validating form submissions and building custom dashboards. As you keep practicing, you might extract this logic into reusable utilities inside a shared helper file for your project.
Conclusion: Master Conditions and Loops to Master JavaScript
Controlling the flow with conditions and loops in JavaScript is not just a basic skill; it is a core competency that shapes everything else you build. Once you are comfortable with if-else, switch, and the main JavaScript loops, you can design logic that is predictable, testable, and easy to extend.
Remember these key points:
- Use if-else for flexible, readable conditions.
- Reach for switch when comparing a single value across many cases.
- Choose the loop type (
for,while,do-while,for...of) based on whether you need indexes, values, or unknown iteration counts. - Leverage break and continue to fine-tune loop behavior.
- Keep control flow clean by avoiding deep nesting and using descriptive helper functions.
With these tools, you are ready to move into more advanced areas like array methods, error handling, and asynchronous flows with promises and async/await, all of which build on the same fundamental idea: controlling the flow of your JavaScript code with confidence.