Skip to content
EzzyWeb

Level 2, Styling & Logic, Chapter 7 of 24

JavaScript Control Flow — Conditionals & Loops

Why this matters

So far your JavaScript has run the same way every single time: line one, then line two, then line three. Real programs rarely work like that. A shipping calculator behaves differently depending on the order total. A form shows an error only if a field is empty. A gallery renders one image element for every photo in a list, however many there are. All of that requires code that can make decisions and repeat itself, which is exactly what conditionals and loops give you.

This chapter combines directly with what you just learned about variables, types, arrays, and comparison operators. A boolean like isLowStock from the last chapter becomes genuinely useful once you can say: if this is true, do one thing, otherwise do another. By the end of this chapter, you'll have everything you need for your Level 2 capstone project, the Digital Business Card, where you'll combine HTML structure, CSS styling, and JavaScript logic into one polished, interactive page.

The lesson

Making decisions with if and else

An if statement runs a block of code only when a condition is true. The condition goes in parentheses after if, and it must evaluate to a boolean, exactly like the comparisons you practiced in the previous chapter. You can follow an if with an else block, which runs only when the condition is false, or with else if to check additional conditions in order. This lets your program branch: different input, different outcome, using the same underlying logic every time. It also helps to know that in a condition, values like 0, an empty string, and undefined are treated as falsy, while most other values are treated as truthy, which is why you'll sometimes see a condition check a value directly, like if (userName), instead of comparing it to something explicitly.

A simple if/else statement
JavaScript
1const total = 42;23if (total >= 50) {4  console.log("You qualify for free shipping!");5} else {6  console.log("Add more items for free shipping.");7}
Only one of the two console.log lines runs, depending on whether the condition is true or false.

You can chain multiple conditions with else if when there are more than two possible outcomes. JavaScript checks each condition from top to bottom and runs the first block whose condition is true, skipping the rest. When you have many possible exact-match values for a single variable, a switch statement can be more readable than a long else if chain: it checks a value against a series of case labels and runs the matching block, falling through to a default block if nothing matches.

Chaining conditions with else if
JavaScript
1const score = 72;2let grade;34if (score >= 90) {5  grade = "A";6} else if (score >= 80) {7  grade = "B";8} else if (score >= 70) {9  grade = "C";10} else {11  grade = "D";12}1314document.querySelector("#grade").textContent = grade;
Only the first true condition runs; the rest are skipped, so order matters when writing else if chains.
A switch statement for exact matches
JavaScript
1const plan = "pro";2let price;34switch (plan) {5  case "free":6    price = 0;7    break;8  case "pro":9    price = 12;10    break;11  case "team":12    price = 29;13    break;14  default:15    price = null;16}1718console.log(price);
Each case checks for an exact match; break stops the switch from falling through into the next case.

Repeating work with loops

A loop repeats a block of code multiple times without you writing it out repeatedly by hand. The for loop is the most common: it has a starting point, a condition that's checked before each repetition, and a step that runs after each repetition. A typical for loop counts upward using a variable, often named i, checking the condition each time and stopping once it becomes false. A while loop is simpler in structure: it just repeats as long as its condition stays true, which is useful when you don't know in advance exactly how many repetitions you'll need.

Counting with a for loop and a while loop
JavaScript
1for (let i = 1; i <= 5; i = i + 1) {2  console.log("Rep number " + i);3}45let remaining = 3;6while (remaining > 0) {7  console.log("Items left: " + remaining);8  remaining = remaining - 1;9}
The for loop runs a known number of times; the while loop keeps going until its condition becomes false.

A common and very readable way to loop over every item in an array is for...of, which hands you each item directly without needing to track an index manually. This pairs naturally with everything you've learned: you might loop over an array of skills and build a piece of text or update the page once for each one, connecting arrays, loops, and DOM updates into a single flow.

Looping over an array with for...of
JavaScript
1const skills = ["HTML", "CSS", "JavaScript"];23for (const skill of skills) {4  console.log("Skill: " + skill);5}
for...of gives you each array item in order, one at a time, without managing an index variable.

Combining conditionals and loops

Conditionals and loops become far more useful once they're nested together. A loop can check a condition on every pass, for example only logging a skill if its name is longer than a certain length, or counting how many items in an array meet some rule. This kind of combination, a loop that makes a decision on each item, is the pattern behind features like filtering a list, validating every field in a form, or highlighting specific items in a gallery.

A loop with a condition inside it
JavaScript
1const scores = [55, 82, 91, 40, 76];2let passingCount = 0;34for (const score of scores) {5  if (score >= 60) {6    passingCount = passingCount + 1;7  }8}910console.log(passingCount + " students passed.");
The if statement runs once per loop iteration, so it evaluates a fresh score each time.

With conditionals and loops, you now have real programming logic to pair with the structure and style from earlier chapters. Your upcoming Level 2 capstone, the Digital Business Card, will ask you to combine HTML for structure, CSS with Flexbox for layout, and JavaScript with conditionals and loops for behavior, such as toggling a section of contact details, looping over an array of skills to log them, or showing a different greeting depending on a condition. Every tool for that project is now in your hands.

Try it yourself

Use an if/else statement to check a value, then use a for...of loop with a condition inside it to display only the skills longer than three characters in the console.

Live preview

Chapter boss project

Boss Project: Level 2 Capstone — Digital Business Card

Build a Digital Business Card: a single page featuring a name, title, short bio, a list of skills or interests, and contact links, all structured with the semantic HTML you learned in earlier chapters and laid out with Flexbox so everything is aligned and well spaced, using the colors, units, and backgrounds from the CSS chapters.

Add at least two pieces of JavaScript logic to the card: one conditional (an if/else, or a switch) and one loop (a for, while, or for...of) that work with data already in your page, such as toggling whether the contact details are shown, changing a greeting based on a condition, or looping over an array of skills to build a list dynamically. Use document.querySelector and classList to connect your JavaScript to the page.

This project pulls together everything from Level 2: selectors, colors, units, and the box model for individual element styling, Flexbox for overall layout, and variables, conditionals, and loops for behavior. Treat it as proof that you can combine structure, style, and logic into one cohesive page.

  • Start with the HTML content first: name, title, bio, a list of skills, and links, using elements from Level 1.
  • Wrap the main sections in a flex container and use gap, justify-content, and align-items to arrange them cleanly.
  • For the toggle feature, use document.querySelector to grab the button and the section to show or hide, and flip a boolean variable each time, using classList.add or classList.remove to reflect the state visually.
  • If you're using a loop to display skills, remember for...of is the most readable option for going through an array one item at a time.
  • Try hsl() colors so you can quickly create a matching lighter or darker shade for hover or highlighted states.

Level-up checklist

Tick these off once each one is true for you.