JavaScript Fundamentals: Loops and Conditionals Explained
The core logic building blocks for every program you write.
Welcome! When you write code, you need a way to make decisions and perform repetitive tasks. In **JavaScript**, these two actions are controlled by **conditional statements** and **loops**. Mastering these two concepts is the absolute foundation of writing functional, dynamic, and efficient programs.
Part 1: Conditional Statements (Making Decisions)
Conditional statements allow your code to execute different blocks of logic based on whether a condition is true or false. The most common form is the **`if/else`** structure.
The `if/else` Statement
This structure evaluates a condition inside the parentheses. If the condition is `true`, the code inside the `if` block runs. If it's `false`, the code inside the `else` block (if present) runs.
let temperature = 25;
if (temperature > 30) {
console.log("It's a hot day!");
} else if (temperature >= 20) {
console.log("It's a pleasant day.");
} else {
console.log("It's a cold day.");
}
Part 2: Loops (Doing Things Repeatedly)
Loops are used to execute a block of code a specific number of times, or as long as a certain condition remains true. This saves you from writing the same code over and over again.
The `for` Loop
The `for` loop is the most common loop. It requires three things: a starting point (initialization), a condition that must be true for the loop to continue, and an increment/decrement step.
// Example: Counting from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5
The `while` Loop
The `while` loop is simpler: it keeps running as long as a specified condition is true. Be careful not to create an **infinite loop** (where the condition never becomes false!).
let counter = 0;
while (counter < 3) {
console.log("Running...");
counter++; // Important: This prevents the infinite loop!
}
// Output: Running... (x3)
By using `if/else` to make decisions and `for/while` to automate repetition, you gain complete control over how your JavaScript programs execute.
Comments
Post a Comment