Learn / Programming / JavaScript / Conditionals and Loops

JavaScript · Lesson 7 of 15

Conditionals and Loops

if/else, switch, for, while, for...of and truthy/falsy values.

  • Beginner
  • 12 min read
  • 3 objectives

Before this lessonLesson 6: The DOM and Events

What you will learn

  • Branch with if and switch
  • Loop with for and for...of
  • Explain truthy and falsy

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 3 hours

Create a free account to keep your progress on every device.

Control flow decides which code runs and how many times. JavaScript has the usual tools plus a few quirks around what counts as true.

if / else and switch

const score = 72;
if (score >= 90) console.log("A");
else if (score >= 70) console.log("B");
else console.log("C");

const day = "sat";
switch (day) {
  case "sat":
  case "sun":
    console.log("weekend");
    break;
  default:
    console.log("weekday");
}
Output
B
weekend

Truthy and falsy

Conditions do not need a boolean. These are falsy: false, 0, "", null, undefined, NaN. Everything else is truthy, including "0", [] and {}.

const name = "";
console.log(name || "anonymous");     // || picks the first truthy
console.log(0 ?? 10);                  // ?? only skips null/undefined
console.log(Boolean([]));
Output
anonymous
0
true

Loops

for (let i = 0; i < 3; i++) console.log("i =", i);

const fruits = ["apple", "pear"];
for (const f of fruits) console.log(f);      // values of an iterable

const user = { id: 1, name: "Ada" };
for (const key in user) console.log(key);    // keys of an object

let n = 3;
while (n > 0) n--;
console.log(n);
Output
i = 0
i = 1
i = 2
apple
pear
id
name
0

Use break to leave a loop early and continue to skip to the next iteration.

Up next · Lesson 8Strings, Numbers and MathString methods, number quirks, parsing and the Math object.