Lesson 3 of 50JavaScript basics
Control Flow
Make decisions with if, ternaries and switch, repeat work with for, while and for...of, and avoid off-by-one bugs.
A program without control flow runs every line once, top to bottom, and then stops. That is fine for a calculator that adds two numbers, but almost nothing real works that way. A checkout page has to decide whether shipping is free. A to-do app has to show every task in a list, however many there are. Control flow is the set of tools that decide which lines run, and how many times. You will use these tools in every program you ever write, so this lesson goes slowly through each one and points out the mistakes that catch beginners and experienced developers alike.
if, else if, else
An if statement runs a block of code only when a condition is true. A condition is any expression that JavaScript can treat as true or false, like total > 50 or user.isAdmin.
Press Run (⌘ Enter) to see what happens.JavaScript checks the conditions in order and runs the first block whose condition is true. Everything after that is skipped, even if a later condition would also be true. That is why the order matters: if you checked total >= 20 first, a $75 order would pay $4.99 shipping, because 75 is also greater than 20. Put the most specific test first.
Try changing the first line inside the function to if (total > 50) and run it again with shippingCost(50). That single character decides whether a $50 order ships free, which is exactly the kind of rule a product manager will ask you about.
A few habits keep if statements readable:
- Always use braces, even for a one-line body.
if (x) doSomething();works, but when someone adds a second line later, only the first one is inside theif. - Return early. Handle the odd cases at the top of a function and
return, so the main logic is not buried three levels deep. - Conditions are converted to true or false.
if ("hello")runs,if (0)does not. The full rules (which values count as "falsy") are in the equality and truthiness lesson. For now, compare explicitly when you can:if (items.length > 0)says more thanif (items.length).
// A if (total >= 50) rate = 0.1; else if (total >= 100) rate = 0.2; // B if (total >= 100) rate = 0.2; else if (total >= 50) rate = 0.1;
The ternary operator
Sometimes you do not want to run different code, you want to pick between two values. The ternary operator (condition ? valueIfTrue : valueIfFalse) does that in one expression. It is called ternary because it takes three parts.
const label = stock > 0 ? "In stock" : "Sold out";Because a ternary produces a value, you can use it anywhere a value fits: inside a template literal, as a function argument, or in JSX in React, where if statements are not allowed. Keep ternaries short. Nesting them (a ? b : c ? d : e) is legal but hard to read; once you need a third option, switch back to if/else if or a lookup object.
switch
A switch compares one value against a list of case values using strict equality (===) and jumps to the first match.
Press Run (⌘ Enter) to see what happens.Two things to notice:
- Stacking cases (
"shipped"and"out-for-delivery") shares one block between several values. That is useful. - Fall-through is the trap. Once a
casematches, JavaScript keeps running every line below it, through the other cases, until it hits abreakor areturn. The second example prints bothmediumandlarge. Inside a function,returnends the switch for you; elsewhere, end every case withbreak.
The default case runs when nothing matches. Always include one, even if it only logs a warning, so a new status from the server does not silently do nothing.
When every case just maps a value to another value, a plain object is often shorter: const MESSAGES = { pending: "We have your order.", shipped: "On the way." } and then MESSAGES[status] ?? "Unknown".
What does this print?
const day = 6;
switch (day) {
case 6:
console.log("Saturday");
case 7:
console.log("Weekend");
break;
default:
console.log("Weekday");
}Choosing between them
You now have four ways to make a decision, and they overlap. A simple rule of thumb: use a ternary when you are choosing between two values; use if/else when you are choosing between two or three actions, or when the conditions are ranges like total >= 50; use switch when one value is compared against many exact options and some options share code; and use a lookup object when every option simply maps to a value. None of them is faster in a way you will ever notice. Pick the one that makes the decision easiest to read at a glance.
Logical operators as control flow
The operators && (and), || (or) and ?? (nullish coalescing) do more than combine true and false. They short-circuit: they stop evaluating as soon as they know the answer, and they return one of their operands, not necessarily a boolean.
a && b: ifais falsy, the result isaandbnever runs. Otherwise the result isb.a || b: ifais truthy, the result isaandbnever runs. Otherwise the result isb.a ?? b: ifaisnullorundefined, the result isb. Otherwise it isa.
Press Run (⌘ Enter) to see what happens.You will see isLoggedIn && showMenu() in real code as a one-line if. Use it for short, obvious cases; a normal if is clearer when the right side does something important. The difference between || and ?? matters a lot with numbers and empty strings, and the destructuring lesson covers it in more depth.
Loops
A loop repeats a block of code. JavaScript has several, and choosing the right one makes your intent obvious.
The classic for loop
for (let i = 0; i < 3; i++) {
console.log(i);
}The parentheses hold three parts, separated by semicolons: a start (let i = 0), a condition checked before every pass (i < 3), and an update that runs after every pass (i++, which adds one). Each pass through the body is called an iteration.
The start expression runs once. Then the condition is checked: 0 < 3 is true.
Put one full iteration of for (let i = 0; i < 2; i++) { work(i); } in order, starting from the very beginning.
- Tap the steps below in the right order.
while and do...while
A while loop only has a condition. Use it when you do not know in advance how many times you will loop: reading until there is no more data, retrying until something succeeds, halving a number until it is small.
let attempts = 0;
while (attempts < 3 && !connected()) {
attempts++;
}Make sure something inside the loop eventually makes the condition false, or the loop runs forever and freezes the page. A do...while loop is the same but checks the condition after the body, so the body always runs at least once. It is rare in practice.
for...of and for...in
for...of walks through the values of anything iterable: arrays, strings, Maps, Sets. It is the loop you will write most often, because there is no counter to get wrong.
for...in walks through the keys (property names) of an object, as strings. It is meant for plain objects, and it is a trap on arrays: you get the indexes as strings ("0", "1"), not the values.
Press Run (⌘ Enter) to see what happens.Remember it as: of gives values, in gives keys ("in" like "is this key in the object?"). For objects, Object.entries(obj) with for...of is often nicer still, since it gives you key and value together.
break exits the loop immediately. continue skips the rest of the current iteration and moves to the next one. Both work in for, while, for...of and for...in.
const colors = ["red", "green"];
for (const c in colors) {
console.log(c);
}Nested loops
A loop inside a loop is called a nested loop. The inner loop runs completely for every pass of the outer one, so a 10 by 10 grid means 100 iterations, and a list of 1,000 users compared against 1,000 orders means a million. That is fine for small data and a common cause of slow pages for large data. When you find yourself writing "for each item, search the whole other list", the maps and sets lesson shows a faster way.
break only exits the innermost loop. To stop both loops at once, either move the loops into a function and return from it, or put a label on the outer loop (outer: for (...)) and write break outer. Labels are rare in everyday code, so a function with an early return is usually the clearer choice.
When a page freezes
If your browser tab stops responding after you change a loop, you have almost certainly written an infinite loop: a condition that never becomes false. Typical causes are forgetting the update (i++), updating the wrong variable, or counting up while checking i >= 0. JavaScript in a page runs on a single thread, so while the loop spins, nothing else can happen: no clicks, no repainting. Close the tab, then check that every path through the loop body moves the condition closer to false.
Off-by-one mistakes
An off-by-one error is a loop that runs one time too many or one time too few. It is so common it has its own name. Almost every case comes from mixing up < and <=, or from forgetting that indexes start at 0.
const names = ["Ada", "Sam", "Leo"];
// Bug: <= runs one extra time, and names[3] does not exist
for (let i = 0; i <= names.length; i++) {
console.log(i, names[i]); // the last line printed is: 3 undefined
}
// Correct: the last index is length - 1
for (let i = 0; i < names.length; i++) {
console.log(i, names[i]);
}
// Counting down needs the same care
for (let i = names.length - 1; i >= 0; i--) {
console.log("reverse:", names[i]);
}The buggy loop does not crash. It quietly logs undefined for index 3, which then flows into your page as the word "undefined" or into a calculation as NaN. Silent wrong answers are worse than errors. Two habits prevent most of these bugs:
- Prefer
for...ofwhen you only need the values. No index means no index to get wrong. - When you do need an index, use the standard shape
for (let i = 0; i < arr.length; i++)every time, so anything different stands out.
A related mistake is the fencepost problem: a 10 metre fence with a post every metre needs 11 posts, not 10. If you are counting the gaps between things, or the things themselves, decide which one before you write the loop.
What does this print?
let count = 0;
for (let i = 1; i <= 10; i += 2) {
count++;
}
console.log(count);- condition
- An expression that is treated as true or false to decide whether code runs.
- ternary
cond ? a : b: an expression that picks one of two values.- fall-through
- In a
switch, running into the next case because the matching case had nobreakorreturn. - short-circuit
&&,||and??stop evaluating once the result is known, so the right side may never run.- iteration
- One pass through the body of a loop.
- for...of / for...in
ofloops over values of an iterable;inloops over the string keys of an object.- off-by-one error
- A loop that runs one time too many or too few, usually from
<=vs<or forgetting indexes start at 0.