Skip to content
  • Control Flow & Loops · JavaScript

Control Flow & Loops

LearnViaNotes @learnvianotes· 2 min read

if/else, switch, the ternary, five kinds of loop, and break/continue with labels.

Conditionals

JavaScript
const grade = (score) => {
  if (score >= 90) return "A";
  else if (score >= 75) return "B";
  else return "C";
};
console.log(grade(95), grade(80), grade(10));
const age = 20;
console.log(age >= 18 ? "adult" : "minor");
Output
A B C
adult

switch uses strict equality and falls through

JavaScript
function kind(day) {
  switch (day) {
    case "sat":
    case "sun":
      return "weekend";
    case 1:
      return "number one";
    default:
      return "weekday";
  }
}
console.log(kind("sun"), kind("mon"), kind(1), kind("1"));

let log = [];
switch (2) {
  case 1: log.push(1);
  case 2: log.push(2);   // no break → falls through
  case 3: log.push(3);
    break;
  case 4: log.push(4);
}
console.log(log);
Output
weekend weekday number one weekday
[ 2, 3 ]

Loops

LoopIterates overUse for
for (init; cond; step)a counterindex-based work, early exit
while (cond)until the condition failsunknown number of iterations
do { } while (cond)at least onceprompts / retries
for (const x of iterable)values of arrays, strings, maps, sets, generatorsthe default for arrays
for (const k in object)enumerable keys (incl. inherited) as stringsplain objects only
arr.forEach(fn)array elementsside effects; cannot break
JavaScript
const arr = ["a", "b"];
arr.extra = "!";
for (const i in arr) console.log("in:", i, typeof i);
for (const v of arr) console.log("of:", v);
for (const [i, v] of arr.entries()) console.log(i, v);
for (const ch of "hi") console.log(ch);
Output
in: 0 string
in: 1 string
in: extra string
of: a
of: b
0 a
1 b
h
i

while / do…while

JavaScript
let n = 1;
while (n < 100) n *= 3;
console.log(n);
let tries = 0;
do {
  tries++;
} while (false);
console.log(tries);
Output
243
1

break, continue and labels

JavaScript
for (let i = 0; i < 6; i++) {
  if (i === 1) continue;
  if (i === 4) break;
  console.log(i);
}
outer: for (let r = 0; r < 3; r++) {
  for (let c = 0; c < 3; c++) {
    if (c === 1) continue outer;
    if (r === 2) break outer;
    console.log(`r${r}c${c}`);
  }
}
Output
0
2
3
r0c0
r1c0

What is the difference between for...in and for...of?

Can you break out of forEach?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report