Control Flow
for...of versus for...in, switch without fallthrough, and try/finally.
if and else
Parentheses are required, braces are not:
const score = 72
if (score >= 90) {
console.log("A")
} else if (score >= 70) {
console.log("B")
} else {
console.log("C")
}A single statement needs no block:
const n = 5
if (n > 0) console.log("positive")for…of
Iterates the values of anything iterable — arrays, strings, Map, Set. The const
is a fresh binding each iteration, not one variable reassigned:
const colors = ["red", "green"]
for (const c of colors) {
console.log(c)
}for…in
Iterates keys, which is what you want for a plain object:
const user = { name: "ada", age: 36 }
for (const key in user) {
console.log(key, user[key])
}On an array it gives you indices, as strings:
const colors = ["red", "green"]
for (const i in colors) {
console.log(i, typeof i)
}Iterating with an index
entries() gives both, destructured in the header:
const colors = ["red", "green", "blue"]
for (const [i, c] of colors.entries()) {
console.log(i, c)
}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:
for (let i = 0; i < 5; i += 2) {
console.log(i)
}while and do…while
let n = 3
while (n > 0) {
console.log(n)
n--
}do...while checks the condition after the body, so it always runs at least once:
let tries = 0
do {
tries++
console.log("attempt", tries)
} while (tries < 2)break, continue, labels
continue skips to the next iteration:
for (const n of [1, 2, 3, 4]) {
if (n % 2 === 0) continue
console.log(n)
}A plain break leaves the inner loop only. A label lets you leave an outer one:
outer: for (const a of [1, 2, 3]) {
for (const b of ["x", "y"]) {
if (a === 2) break outer
console.log(a, b)
}
}switch
Cases fall through unless you stop them. Without break, matching "editor" also
runs everything below it:
const role = "editor"
switch (role) {
case "admin":
console.log("can delete")
case "editor":
console.log("can edit")
case "viewer":
console.log("can read")
}With break, and a default for no match:
const role = "editor"
switch (role) {
case "admin":
console.log("can delete")
break
case "editor":
console.log("can edit")
break
default:
console.log("no access")
}Stacked cases are the one time fallthrough is what you want:
const day = "sat"
switch (day) {
case "sat":
case "sun":
console.log("weekend")
break
default:
console.log("weekday")
}Matching is strict, so no conversion happens:
const n = "1"
switch (n) {
case 1:
console.log("number one")
break
default:
console.log("no match")
}Short-circuiting as control flow
&& and || stop evaluating as soon as the answer is known, which makes them a
conditional in one line:
const logger = null
logger?.log("ignored")
const items = []
items.length && console.log("has items")
const name = ""
console.log(name || "anonymous")