Sikau

JavaScript · Day 12 · about 25 min

if and else

If it rains, take an umbrella.

Code that chooses

Every morning you make little decisions: if it's raining, take an umbrella; otherwise, wear sunglasses. Until now your code ran every line, top to bottom. Today it learns to choose.

The if statement

An if statement runs a block of code only when a condition is true.

const raining = true;

if (raining) {
  console.log("Take an umbrella ☔");
}
console.log("Have a good day!");

Change true to false and run it again. The umbrella line disappears, but "Have a good day!" stays.

The rest of this lesson

  • Otherwise: elseexplain
  • Blocks, braces and indentationexplain
  • Predict the outputpredict
  • Which lines run?predict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript