JavaScript + Node.js track

Lesson 04 · Part 1: Basics

Control Flow

`if`/`switch`/`for`/`while`/`for...of`/`for...in`

Part 1: Basics2 min readFree lesson

Step: Basics | Player: 03_Operators and_Expressions

Learning Objectives

  • You can branch the condition with if / else if / else.
  • Understand the switch statement and its pitfalls (break is missing).
  • Distinguish between for, while, for...of, and for...in.
  • You can control the repeat flow with break and continue.
  • You can write simple conditional expressions with the ternary operator.

1. Conditional branch if / else

The condition evaluates to truthy/falsy. If the branches become longer than 3, consider replacing them with switch or Data (object mapping).

if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";

2. switch

Branch to case where the value matches exactly. If you omit break at the end of each case, it will fallthrough to the next case. Please indicate intentional fallthrough in comments.

switch (day) {
  case "Sat":
  case "Sun":
    console.log("weekend");
    break;
  default:
    console.log("weekdays");
}

3. Loop statement

  • for (let i = 0; i < n; i++) — When an index is needed.
  • while (cond) — When only the termination condition is clear.
  • for...of — Traverse iterable values such as arrays and strings.
  • for...in — Key traversal of objects (not recommended for arrays).
for (const ch of "JS") console.log(ch);
for (const key in { a: 1, b: 2 }) console.log(key);

4. break / continue / ternary

break terminates the loop immediately, and continue skips the current round. The ternary operator is concise when determining a value based on a condition.

const label = age >= 18 ? "adult" : "minor";

Core example

file Contents covered
01_if_else.js Grade branching by score + ternary
02_switch.js switch fallthrough and group case
03_for_loops.js for, while, for...of, for...in comparison
04_break_continue.js Skip Even and Quit Early

⚠️ Common Mistakes

  1. Unintended fallthrough occurs due to omission of break at the end of each case in switch.
  2. When using for (var i ...) and asynchronous callback together, i is shared and a bug occurs (using let).
  3. Problem that the index is displayed as a string or the order is not guaranteed when using for...in in the array.
  4. Omitting to change the exit condition after creating an infinite loop.
  5. Code that overlaps too many ternaries, making it difficult to read.

❓ Frequently Asked Questions (FAQ)

Q1. Should I use for or forEach? A. If you need break in the middle, use for/for...of. For simple traversal, forEach is also good.

Q2. Should switch always be avoided? A. It is easier to read if the branches are clearly value-based. If your branching becomes complex, switch to object mapping.

Q3. Doesn't continue confuse the code flow? A. When reducing deep nesting with guard clauses, it actually improves readability.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_if_else.jsJavaScript
/** Grades are divided according to scores.*/
function grade(score) {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}

for (const s of [95, 82, 71, 60, 45]) {
  const pass = s >= 60 ? "passed" : "failed";
  console.log(`${s} points → ${grade(s)} (${pass})`);
}
src/02_switch.jsJavaScript
/** Shows the group case and fallthrough of the switch.*/
function describe(day) {
  switch (day) {
    case "Mon":
    case "Tue":
    case "Wed":
    case "Thu":
    case "Fri":
      return "weekdays";
    case "Sat":
    case "Sun":
      return "weekend";
    default:
      return "unknown";
  }
}

for (const d of ["Mon", "Sat", "Xyz"]) {
  console.log(d, "→", describe(d));
}
src/03_for_loops.jsJavaScript
/** Compare four iteration methods.*/
const arr = ["a", "b", "c"];

//1) Traditional for
for (let i = 0; i < arr.length; i += 1) {
  console.log("for", i, arr[i]);
}

// 2) while
let i = 0;
while (i < arr.length) {
  console.log("while", arr[i]);
  i += 1;
}

//3) for...of (value traversal - recommended for arrays/iterables)
for (const v of arr) console.log("for...of", v);

//4) for...in (key traversal - recommended for objects)
const obj = { x: 1, y: 2 };
for (const key in obj) console.log("for...in", key, "=", obj[key]);
src/04_break_continue.jsJavaScript
/** Skip even numbers with continue, terminate early with break.*/
for (let i = 1; i <= 10; i += 1) {
  if (i % 2 === 0) continue;
  if (i > 7) break;
  console.log("Odd:", i);
}

//guard clause pattern
function greet(name) {
  if (!name) return "There is no name";
  return `Hello, ${name}!`;
}
console.log(greet(""));
console.log(greet("Ada"));

Assignment

homework_01.js — FizzBuzz

  • Prints from 1 to 30,
  • "Fizz" if it is a multiple of 3
  • "Buzz" if it is a multiple of 5
  • If it's both, it's "FizzBuzz"
  • Otherwise, print the number itself.

homework_02.js

  • Aggregate the score array [92, 78, 65, 88, 55, 100] by grade (A~F) and output it as an object.
  • Example: { A: 2, B: 1, C: 1, D: 1, F: 1 }
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/** FizzBuzz 1~30 */
for (let i = 1; i <= 30; i += 1) {
  if (i % 15 === 0) console.log("FizzBuzz");
  else if (i % 3 === 0) console.log("Fizz");
  else if (i % 5 === 0) console.log("Buzz");
  else console.log(i);
}
homework_02.jsJavaScript
/** The score array is aggregated by grade.*/
function gradeOf(score) {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}

const scores = [92, 78, 65, 88, 55, 100];
const summary = { A: 0, B: 0, C: 0, D: 0, F: 0 };

for (const s of scores) {
  summary[gradeOf(s)] += 1;
}

console.log(summary);

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now