Control Flow in JavaScript
Master conditionals, switch statements, loops, and loop control in JavaScript with practical Docker-ready Node.js examples
Control flow is how a program decides what to do and how many times to do it. Without it, code would simply run top to bottom with no branching or repetition. JavaScript gives you a familiar, C-inspired set of structured control-flow tools: if/else, switch, and several flavors of loops.
As a multi-paradigm, dynamically-typed language, JavaScript layers a few distinctive features on top of the classic structures. Conditions are evaluated using truthiness rather than requiring a strict boolean, so values like 0, "", null, and undefined all count as “false.” The logical operators &&, ||, and the nullish-coalescing ?? operator short-circuit, which lets you express defaults and guards concisely. And because JavaScript is weakly typed, understanding how values coerce inside a condition is essential to writing correct branches.
This tutorial walks through conditionals, the switch statement, every loop form (for, while, do...while, for...of, for...in), loop control with break and continue, and the truthiness rules that make JavaScript conditions behave the way they do. Every example is a standalone file you can run with Node.js or Docker.
Conditionals: if, else if, else, and the Ternary
The if statement runs a block only when its condition is truthy. Chain else if for additional branches and else for a fallback. For simple either/or choices, the ternary operator condition ? a : b produces a value inline.
Create a file named conditionals.js:
| |
The if chain evaluates conditions top to bottom and runs the first matching block. The ternary is an expression, so it can be assigned directly to a variable — unlike if, which is a statement.
The switch Statement
When you compare a single value against many fixed possibilities, switch is often clearer than a long if/else if chain. Each case is compared using strict equality (===). A break ends the switch; omitting it causes fall-through, which is useful for grouping cases that share behavior.
Create a file named switch_demo.js:
| |
Because case uses strict equality, switch (1) will not match case "1" — the number and string are different types. The default clause handles any unmatched value and can appear anywhere, though it’s conventionally placed last.
Loops: for, while, do…while, for…of, for…in
JavaScript offers several looping constructs. The classic for loop gives explicit control over a counter. while repeats as long as a condition holds, and do...while is its cousin that always runs the body at least once. For collections, for...of iterates over the values of an iterable (like an array), while for...in iterates over the keys of an object.
Create a file named loops.js:
| |
A common mistake is using for...in on an array expecting the elements — it actually yields the indices as strings. Use for...of for array values and for...in for object property names.
Loop Control: break, continue, and Labels
break exits a loop immediately, and continue skips the rest of the current iteration and moves to the next. For nested loops, a label lets break or continue target an outer loop instead of the innermost one.
Create a file named loop_control.js:
| |
Without the outer: label, break would only exit the inner col loop and the outer loop would keep running. Labeled statements are rarely needed, but they’re the cleanest way to break out of deeply nested iteration.
Truthiness and Short-Circuit Logic
JavaScript conditions don’t require a boolean — any value is coerced to true or false. The falsy values are exactly: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy. The || operator returns the first truthy operand (great for defaults), while ?? (nullish coalescing) only falls back when the left side is null or undefined — not for other falsy values like 0.
Create a file named truthiness.js:
| |
This example highlights a subtle but important distinction: count || 10 gives 10 because 0 is falsy, but count ?? 10 gives 0 because the value is neither null nor undefined. Reach for ?? when 0, "", or false are legitimate values you want to keep.
Running with Docker
You can run every example without installing Node.js locally by using the official Node.js Alpine image.
| |
If you have Node.js installed locally (v18+), run any file directly, for example: node conditionals.js.
Expected Output
$ node conditionals.js
Comfortable
It feels warm
Grade: B
$ node switch_demo.js
Day 3 is Wednesday
Month 4 is in Spring
$ node loops.js
for loop: 1
for loop: 2
for loop: 3
while count: 3
while count: 2
while count: 1
do...while: 0
do...while: 1
color: red
color: green
color: blue
name = Ada
role = engineer
$ node loop_control.js
break demo: 1
break demo: 2
break demo: 3
break demo: 4
break demo: 5
odd number: 1
odd number: 3
odd number: 5
stopping at row 1, col 3
$ node truthiness.js
0 is falsy
"" is falsy
"hello" is truthy
null is falsy
42 is truthy
Welcome, Guest
OR result: 10
Nullish result: 0
Key Concepts
- Conditions use truthiness, not strict booleans —
0,"",null,undefined,NaN, andfalseare falsy; everything else is truthy. - The ternary
? :is an expression — it produces a value you can assign, unlikeif, which is a statement. switchcompares with strict equality (===) — types must match, and missingbreakcauses intentional (or accidental) fall-through.- Pick the right loop for the job —
forfor counters,while/do...whilefor condition-driven repetition,for...offor array values,for...infor object keys. for...inyields keys, not values — using it on an array gives string indices, which is a frequent source of bugs; preferfor...offor arrays.breakandcontinuecontrol loops —breakexits,continueskips an iteration, and labels let them target an outer loop in nested code.||vs??matters —||falls back on any falsy value, while??only falls back onnull/undefined, preserving valid0and""values.
Comments
Loading comments...
Leave a Comment