JavaScript 101: Getting Started with Control Flow
Source: Dev.to
TL;DR
- In your applications, the control flow is the one in charge of making sure your code is taking the right path.
if,else if, andelsehelp run different code depending on conditions. - You’ll usually combine control flow with comparison or logical operators (coming up in the next article!).
- Good control flow helps avoid messy, repetitive code.
Getting started
Writing code is basically telling the computer what to do, one step at a time. But what if you have to decide something based on the data that will change the steps that the computer needs to take? How do you tell the computer, “hey, when this happens, do this or that”? That is exactly where control flow comes into play. It makes sure your code is able to decide what to do based on certain conditions.
In this article, I’ll walk you through the most basic building blocks for making decisions in JavaScript: if, else if, and else.
💡 Before we jump in: these statements work hand‑in‑hand with operators like ==, >, or &&. If those look a little fuzzy right now, don’t worry—we’ll cover operators in the next article.
What Is Control Flow?
Control flow is a fancy term for how your code “flows” from one process to the next.
By default, JavaScript runs code from top to bottom, line by line. Using conditional statements, we can interrupt, modify, or even reset that flow by telling our program:
- “If this is true, do this.”
- “Otherwise, maybe do that.”
- “If none of the above, do this other thing instead.”
The if statement
The if statement is straightforward: if a condition is true, run the associated code.
if (condition) {
// code to run if condition is true
}
Example
let score = 90;
// Passes only if strictly greater than 70 (70 fails)
if (score > 69) {
console.log("Not bad.");
}
// Passes if it is higher or equal to 70 (70 passes)
if (score >= 70) {
console.log("Not bad.");
}
In the example, JavaScript checks if score is larger than 70 and prints “Not bad.” If the condition is false, it skips the block.
The else if and else statements
When you need multiple conditions, chain else if and finish with an else as a fallback.
if (score > 80) {
console.log("Nice job!");
} else if (score > 70) {
console.log("Not bad.");
} else {
console.log("Keep practicing.");
}
This lets your code pick between several paths. JavaScript stops checking once it finds a match.
Pro Tips to Keep Your Conditions Clean
- Keep conditions simple; if they become messy, break them into well‑named variables.
- You can nest
ifstatements, but avoid deep nesting—it makes code hard to read. - Always test all branches of your conditions.
Coming Next: Operators in JavaScript
In the next part, we’ll dig into how JavaScript manages operators and see how they pair with if, else if, and else to create proper data flows.
