Back to Blog
Loops and Conditionals in JavaScript Programming
May 20, 20268 min read

Loops and Conditionals in JavaScript Programming

You have written a loop or an if statement in JavaScript, it runs, and it does the wrong thing — skips a value, runs one time too many, or takes a branch you did not expect. This is one of the most common places new JavaScript developers get stuck, and it is rarely because the concept is hard. It is because JavaScript's rules for what counts as 'true' and how it compares values have some sharp edges, and one wrong assumption sends your logic off the rails.

Loops and conditionals are how a program makes decisions and repeats work — the point where code becomes genuinely capable. This guide covers how to write them correctly in JavaScript, and especially the truthy/falsy and coercion traps that make loops and conditions misbehave in ways that are baffling until you know the cause.

Conditionals, and the truthy/falsy trap

An if statement runs a block when a condition is true, and JavaScript lets you put almost any value in that condition — not just true or false. It decides based on 'truthiness', and the rules are specific enough to catch beginners constantly. A small set of values are 'falsy': 0, the empty string, null, undefined, NaN, and false itself. Everything else is 'truthy'.

if ("") console.log("runs?");   // no -- empty string is falsy
if ("0") console.log("runs?");  // YES -- the STRING '0' is truthy!
if ([]) console.log("runs?");   // YES -- empty array is truthy

The traps here are sharp. The string '0' is truthy even though the number 0 is falsy. An empty array is truthy, even though it 'feels' empty. These catch people because the intuition is wrong, and the resulting bugs — a check that passes when you expected it to fail — are hard to spot. Learning JavaScript's exact falsy list, and that anything not on it is truthy, is what turns these from mysterious bugs into predictable behaviour.

A condition that clearly should be false somehow runs anyway — this is one of the most maddening experiences in early JavaScript, and it almost always comes down to a truthy/falsy or coercion rule you have not met yet. Hunting for it alone can eat an entire study session. A tutor who has debugged this exact thing dozens of times spots it at a glance. That is what our one-on-one JavaScript help is built to do — get you unstuck and back to building.

Comparisons in conditions: === again

The equality rules from JavaScript's type system show up right here in your conditions, and they are the biggest source of logic bugs. Because loose equality (==) coerces types before comparing, a condition can be true when you are certain it should be false. This is where the strict-equality habit pays off most visibly.

if (0 == "")  console.log("equal?");  // runs -- both coerce to falsy
if (0 === "") console.log("equal?");  // does NOT run -- different types
if ([] == false) console.log("huh");   // runs -- array coerces!

An empty array loosely equals false; zero loosely equals an empty string. These are not edge cases you will avoid by luck — they appear in real conditions and produce branches that take the wrong path. Using strict equality (===) in every condition removes the entire problem, because it never coerces. If your loop or if statement is behaving impossibly, a loose == comparison is the first thing to suspect and the easiest to fix.

The for loop, done right

The classic for loop gives you full control: a starting point, a condition to keep going, and a step. It is ideal when you know how many times to repeat, but its three parts are also where off-by-one errors breed — the most common bug in all of programming.

let total = 0;
for (let i = 0; i < 5; i++) {   // i goes 0,1,2,3,4 -- NOT 5
  total += i;
}
console.log(total);   // 10

The condition i < 5 means the loop runs for i equal to 0, 1, 2, 3 and 4 — five times, stopping before 5. Beginners constantly get this boundary wrong, using <= when they meant <, or starting from 1 instead of 0, and the result is a loop that runs one time too many or too few. Being deliberate about the start value and whether the condition uses < or <= is the fix, and using let (not var) for the loop counter avoids a separate scope bug that var introduces. When a loop produces almost-right output — the right values but one extra, or missing the last one — an off-by-one boundary is nearly always the culprit, and it is worth checking first.

for...of and the modern loops

When you just want to do something with each item in an array, modern JavaScript offers cleaner loops than the classic for. The for...of loop walks directly over the values, with no counter to manage and no boundary to get wrong — which eliminates the off-by-one error entirely for the common case.

const scores = [80, 92, 75];
let total = 0;
for (const s of scores) {   // s is each value in turn
  total += s;
}
console.log(total);   // 247

There are also array methods like forEach, map and filter that express common loop patterns even more clearly, and you will see them everywhere in real JavaScript. For a beginner, the progression is worth understanding: master the classic for loop and why its boundaries matter, then adopt for...of and the array methods for cleaner code. Knowing which loop fits a task — full control versus simple iteration — is part of writing JavaScript that reads well and works right.

while loops and the infinite-loop danger

A while loop repeats as long as its condition stays true, which suits situations where you do not know the count in advance. Its danger is the infinite loop: if nothing inside the loop ever makes the condition false, it runs forever and freezes the page — a genuinely alarming experience for a beginner whose browser tab locks up.

let n = 8;
let steps = 0;
while (n > 1) {
  n = Math.floor(n / 2);   // MUST move toward stopping
  steps++;
}
console.log(steps);   // 3

Every while loop needs a clear answer to 'what will eventually make this stop?' Here n shrinks each pass until it reaches 1. Forgetting to change the condition variable inside the loop — leaving n the same every time — is the classic mistake, and it hangs the program. Before running any while loop, check that something inside it moves the condition toward false. That single habit prevents the frozen-tab experience that scares off so many beginners.

switch: choosing among many options

When you need to check one value against many possibilities, a long chain of if/else if statements gets hard to read, and JavaScript offers the switch statement as a cleaner alternative. It compares a single value against a list of cases and runs the matching one — but it comes with a famous trap that catches nearly every beginner.

switch (day) {
  case "Sat":
  case "Sun":
    console.log("Weekend");
    break;          // WITHOUT break, it 'falls through'
  default:
    console.log("Weekday");
}

The trap is that each case needs a break statement, or execution 'falls through' into the next case and keeps running — a source of genuinely confusing bugs where more code runs than you intended. This fall-through is occasionally useful (grouping cases, as with the weekend above), but forgetting break when you did not mean to is a classic mistake. Knowing that switch requires break, and why leaving it out causes fall-through, lets you use this cleaner structure without falling into its one sharp edge.

Combining conditions with && and ||

Real conditions often depend on several things at once, and JavaScript combines them with && (and), || (or), and ! (not). The behaviour worth understanding deeply is short-circuiting: these operators stop evaluating as soon as the result is certain, which is both an efficiency feature and a widely-used trick.

const name = "" || "Guest";   // '' is falsy, so name becomes 'Guest'
const safe = user && user.age; // only reads user.age if user exists
console.log(name);             // 'Guest'

Because || returns the first truthy value, it is commonly used to supply a default when something is empty. Because && stops at the first falsy value, it is used to safely access something only if a prior check passes. These patterns appear constantly in real JavaScript, and understanding that the logical operators return actual values (not just true/false) and short-circuit is what lets you read and write the concise, idiomatic conditions that professional code is full of.

Where JavaScript beginners actually go wrong with control flow

  • Not knowing the falsy list, so conditions on '0', empty arrays, or empty strings behave unexpectedly.
  • Using == in conditions and getting coerced, wrong-path results.
  • Off-by-one errors from < versus <=, or starting the counter at the wrong value.
  • while loops with no way for the condition to become false, freezing the page.
  • Using var for loop counters, introducing scope bugs let would avoid.

How to master JavaScript loops and conditionals

  • Learn the exact falsy values; treat everything else as truthy.
  • Use === in every condition so coercion never sends you down the wrong branch.
  • Check loop boundaries deliberately — start value, and < versus <=.
  • Prefer for...of and array methods for iterating over collections.
  • For every while loop, confirm what will make it stop before you run it.

Get your logic working, faster

When a loop runs one time too many or a condition takes the wrong branch, the problem is rarely your intelligence and almost always a specific rule — a boundary, a falsy value, a loose comparison. Learners who get those rules explained clearly stop losing hours to logic bugs and start making real progress. Our JavaScript tutoring across Metro Vancouver and online works through your own misbehaving loops and conditions, so you leave each session with code that runs and the understanding of why.

The easiest first step is a conversation that costs nothing. Book a free 30-minute consultation, bring the loop or condition that is fighting you, and we will find the exact issue and show you how quickly it is fixed — online, or in person in Burnaby with free parking.

Recommended Reads

Book a Free 30-Minute Consultation

Use the form below and a member of our team will respond within the next 24 hours.

Or

Prefer Quick Communication? Message Us On Whatsapp Or Call Us!

Chat With Us On Whatsapp+1 672-514-7587
Chat with us