VS Vikesh Singh

Courses JavaScript Lesson 9

JAVASCRIPT · LESSON 9 OF 18

Conditionals and Loops Without Overcomplicating Code

· 2 min read

You've written variables, functions, arrays, and objects by now.

You've written variables, functions, arrays, and objects by now. What's been missing is control: making your code decide things and repeat things, instead of running the same lines top to bottom every single time. That's what conditionals and loops give you, and despite the intimidating-sounding names, the ideas are simple once you see them written plainly.

Making Decisions With If And Else

Start with if. It runs a block of code only when a condition is true, and skips it otherwise.

let age = 20;
if (age >= 18) {
 console.log("You can vote, " + "Vikesh Singh");
}

The condition inside the parentheses is evaluated, and if it comes out truthy, the block in curly braces runs. If it doesn't, JavaScript just moves past the block entirely, as if it wasn't there. You almost never leave it at just "if" though, because real decisions usually have more than one branch.

let score = 72;
if (score >= 90) {
 console.log("Grade: A");
} else if (score >= 70) {
 console.log("Grade: B");
} else {
 console.log("Grade: C or below");
}

JavaScript checks each condition in order, top to bottom, and runs the first block whose condition is true, then skips the rest entirely — it doesn't keep checking after it finds a match. That's an important detail beginners miss: if score were 95, it matches the first condition and the "B" and "C" branches never even get evaluated. The final else is a catch-all, with no condition of its own, that runs only if nothing above it matched.

Using Switch For Many Fixed Values

A common habit worth building early: don't chain more than three or four else if blocks if you can avoid it. When you've got many fixed possible values to check against one variable, a switch statement reads more clearly than a long if/else if ladder.

let hero = "Iron Man";
switch (hero) {
 case "Iron Man":
 console.log("Real name: Tony Stark");
 break;
 case "Captain America":
 console.log("Real name: Steve Rogers");
 break;
 default:
 console.log("Unknown hero");
}

switch compares the value in parentheses against each case using strict equality (the same kind === uses), and runs the matching block. The break at the end of each case matters more than it looks like it should: without it, execution "falls through" into the next case below, running that code too, even though its condition was never checked. That's rarely what you want, so get in the habit of putting break at the end of every case except when you're deliberately using fall-through on purpose. default works like else — it catches anything that didn't match any case above it.

Looping With For And While

Now, loops — these repeat a block of code instead of branching once. The classic one is the for loop, built for when you know (or can calculate) how many times you need to repeat something.

for (let i = 1; i <= 5; i++) {
 console.log("Count: " + i);
}

Reading this left to right: let i = 1 runs once at the very start. i <= 5 is checked before every single pass — if it's false, the loop stops immediately without running that pass. i++ runs after every pass, incrementing i by one. So this prints Count: 1 through Count: 5, then stops once i becomes 6 and the condition fails. The three parts — setup, condition, step — are what make a for loop predictable: you can tell exactly how many iterations will happen just by reading that one line. while is simpler in shape but needs more care from you. It just keeps running as long as its condition stays true, with no built-in setup or step — you're responsible for both.

let energy = 3;
while (energy > 0) {
 console.log("Vikesh Singh is training, energy left: " + energy);
 energy--;
}

Notice energy-- lives inside the loop body here, not in the loop's own header like a for loop's i++. If you forgot that line, energy would never change, the condition would always stay true, and you'd have an infinite loop — one of the most common beginner mistakes, and one that will genuinely freeze your browser tab if it happens on a page. Whenever you write a while loop, immediately ask yourself: what, inside this loop, changes the condition so it eventually becomes false? If you can't answer that, you've probably got a bug.

Looping Over Arrays And Objects

Arrays and objects each get their own loop built specifically for them. for...of walks through the values in anything iterable, like an array, one at a time — it's the one you'll reach for constantly.

let avengers = ["Iron Man", "Thor", "Black Widow"];
for (let member of avengers) {
 console.log(member + " is ready.");
}

No index variable, no length checking, no off-by-one risk — you just get each value directly. Compare that to looping with a classic for loop over the same array (for (let i = 0; i < avengers.length; i++) { console.log(avengers[i]); }), which works fine too, but needs you to manage the index yourself and is more useful when you actually need that index for something, like knowing a value's position. for...in is easy to confuse with for...of because the names look nearly identical, but it does something different: it loops over the keys of an object, not the values of an array.

let hero = { name: "Tony Stark", alias: "Iron Man", power: "Genius intellect" };
for (let key in hero) {
 console.log(key + ": " + hero[key]);
}

Here key takes on "name", then "alias", then "power" in turn, and hero[key] looks up the value for each one using bracket notation from the arrays lesson. A frequent beginner mix-up: using for...in on an array. It technically works, because array indexes are keys too, but it hands you indexes as strings and isn't meant for this job — stick to for...of for arrays, and for...in for plain objects, and you'll avoid a whole category of confusing bugs later.

Break And Continue

One more control-flow word worth knowing now: break stops a loop entirely and jumps past it, while continue skips just the current pass and moves on to the next one. Both work inside for, while, and for...of loops the same way.

for (let number of [1, 2, 3, 4, 5]) {
 if (number === 3) {
 continue;
 }
 if (number === 5) {
 break;
 }
 console.log(number);
}

This prints 1, 2, and 4 — continue skips printing 3 but keeps looping, while break stops the whole loop as soon as it hits 5, so 5 never gets printed either. Give it a try: build an array of a few superhero names, including "Iron Man", and loop over it with for...of. Inside the loop, use an if/else if/else chain to print a different message for "Iron Man" than for everyone else. Then rewrite the same message logic using a switch statement instead, and see which one reads more clearly for this particular case.