Conditionals

Programming Languages · JavaScript Basics · 12 min

Let your code make decisions with comparisons, if / else and the ternary.

True or false?

A comparison asks a question and answers true or false (a boolean). > < >= <= compare sizes. === asks "exactly equal?" and !== asks "not equal?".

JavaScript also has ==, which converts types first, so 5 == "5" is true. That causes sneaky bugs, so always use ===.

  • Print age >= 18.

  • Print 5 == "5" and then 5 === "5" to see the difference.

if and else

if runs a block of code only when its condition is true. else runs when it's false. The block lives between { }.

if (isRaining) {
  console.log("Take an umbrella");
} else {
  console.log("Enjoy the sun");
}
  • If temperature is greater than 25, print Hot day. Otherwise print Nice day.

More choices: else if

else if adds another check between if and else. JavaScript tries each condition from the top and runs the first one that's true, then skips the rest.

if (speed > 100) {
  console.log("Fast");
} else if (speed > 50) {
  console.log("Medium");
} else {
  console.log("Slow");
}
  • Print A if score is 90 or more, B if it's 70 or more, and C otherwise.

And, or, not

Combine conditions:

  • && (and): true only if both sides are true.
  • || (or): true if at least one side is true.
  • ! (not): flips true to false and back.
if (hungry && hasFood) {
  console.log("Eat!");
}
  • If hasTicket is true and age is 18 or more, print Welcome in.

  • If isWeekend or isHoliday is true, print Sleep in.

  • Print !isWeekend.

The ternary: a one-line if

When you just need to pick between two values, the ternary is a shortcut: condition ? valueIfTrue : valueIfFalse.

let hour = 9;
const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(greeting); // Good morning
  • Create label with a ternary: "even" if n % 2 === 0, otherwise "odd".

  • Print label.

Put it together: ticket booth

Kids under 13 pay 5, everyone else pays 10. Kids and students get a discount ticket. Use a ternary for the price and if / else with || for the ticket type.

  • Create price with a ternary: 5 if age < 13, otherwise 10.

  • If age < 13 or isStudent, print Discount ticket. Otherwise print Full ticket.

  • Print Price: followed by price, like Price: 5.

More in JavaScript Basics

Previous: Strings and Numbers · Next: Functions