Code of the Day
BeginnerLanguage basics

Control flow

Conditionals, loops, and the truthiness rules that drive them.

JavaScript / TSBeginner8 min read
Recommended first
By the end of this lesson you will be able to:
  • Branch with if/else and iterate with for-of
  • Use === over == and understand truthiness
  • Iterate arrays with for-of and forEach

The three universal shapes of logic — sequence, selection, iteration (the fundamentals lesson) — in JavaScript syntax. Blocks are delimited by { }, and conditions live in ( ).

Selection: if / else

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

Use === not ==

JavaScript has two equality operators, and this trips up everyone:

  • === compares value and type, with no surprises: 1 === "1" is false.
  • == coerces types first, producing oddities like 1 == "1" being true and 0 == "" being true.

Always use === (and !==). The coercing == causes subtle bugs.

Truthiness

In a condition, every value is "truthy" or "falsy." The falsy values are worth memorising: false, 0, "", null, undefined, and NaN. Everything else is truthy — a quirk tied to JavaScript's . This is why if (items.length) reads as "if there are any items."

Loops over arrays

For iterating a collection, for...of is the clean, modern choice:

const names = ["Ada", "Alan"];
for (const name of names) {
  console.log(name);
}

Arrays also have forEach (and map/filter you'll meet next), which take a function per element:

names.forEach((name) => console.log(name));
JavaScript — editable, runs in your browser

Where to go next

Next: strings and template literals — working with text the modern way.

Finished reading? Mark it complete to track your progress.

On this page