Skip to content
Sign inGet all access
Chapter 3·14 minFree

Control Flow

for...of versus for...in, switch without fallthrough, and try/finally.

if and else

Parentheses are required, braces are not:

app.mjs
const score = 72

if (score >= 90) {
  console.log("A")
} else if (score >= 70) {
  console.log("B")
} else {
  console.log("C")
}
OutputB

A single statement needs no block:

app.mjs
const n = 5

if (n > 0) console.log("positive")
Outputpositive

for…of

Iterates the values of anything iterable — arrays, strings, Map, Set. The const is a fresh binding each iteration, not one variable reassigned:

app.mjs
const colors = ["red", "green"]

for (const c of colors) {
  console.log(c)
}
Outputredgreen

for…in

Iterates keys, which is what you want for a plain object:

app.mjs
const user = { name: "ada", age: 36 }

for (const key in user) {
  console.log(key, user[key])
}
Outputname adaage 36

On an array it gives you indices, as strings:

app.mjs
const colors = ["red", "green"]

for (const i in colors) {
  console.log(i, typeof i)
}
Output0 string1 string

Iterating with an index

entries() gives both, destructured in the header:

app.mjs
const colors = ["red", "green", "blue"]

for (const [i, c] of colors.entries()) {
  console.log(i, c)
}
Output0 red1 green2 blue

The C-style for still exists, and is right when you step by something other than one. Its three clauses are the one place semicolons are mandatory:

app.mjs
for (let i = 0; i < 5; i += 2) {
  console.log(i)
}
Output024

while and do…while

app.mjs
let n = 3

while (n > 0) {
  console.log(n)
  n--
}
Output321

do...while checks the condition after the body, so it always runs at least once:

app.mjs
let tries = 0

do {
  tries++
  console.log("attempt", tries)
} while (tries < 2)
Outputattempt 1attempt 2

break, continue, labels

continue skips to the next iteration:

app.mjs
for (const n of [1, 2, 3, 4]) {
  if (n % 2 === 0) continue

  console.log(n)
}
Output13

A plain break leaves the inner loop only. A label lets you leave an outer one:

app.mjs
outer: for (const a of [1, 2, 3]) {
  for (const b of ["x", "y"]) {
    if (a === 2) break outer

    console.log(a, b)
  }
}
Output1 x1 y

switch

Cases fall through unless you stop them. Without break, matching "editor" also runs everything below it:

app.mjs
const role = "editor"

switch (role) {
  case "admin":
    console.log("can delete")
  case "editor":
    console.log("can edit")
  case "viewer":
    console.log("can read")
}
Outputcan editcan read

With break, and a default for no match:

app.mjs
const role = "editor"

switch (role) {
  case "admin":
    console.log("can delete")
    break
  case "editor":
    console.log("can edit")
    break
  default:
    console.log("no access")
}
Outputcan edit

Stacked cases are the one time fallthrough is what you want:

app.mjs
const day = "sat"

switch (day) {
  case "sat":
  case "sun":
    console.log("weekend")
    break
  default:
    console.log("weekday")
}
Outputweekend

Matching is strict, so no conversion happens:

app.mjs
const n = "1"

switch (n) {
  case 1:
    console.log("number one")
    break
  default:
    console.log("no match")
}
Outputno match

Short-circuiting as control flow

&& and || stop evaluating as soon as the answer is known, which makes them a conditional in one line:

app.mjs
const logger = null
logger?.log("ignored")

const items = []
items.length && console.log("has items")

const name = ""
console.log(name || "anonymous")
Outputanonymous