Skip to content
BetaDE
Lesson 2 of 11JavaScript

JavaScript · Lesson 2 · 25 minutes

Decisions with if

What you'll learn

  • Branch with if, else if and else
  • Compare values with ===
  • Combine conditions with && and ||

if, else if, else

The condition goes in round brackets, the code that belongs to it in curly ones:

const temperature = 23;

if (temperature > 25) {
  console.log("Swimming pool!");
} else if (temperature > 15) {
  console.log("T-shirt weather.");
} else {
  console.log("Put a jacket on!");
}

Python comparison: instead of a colon and indentation, JavaScript uses curly brackets { }. And elif becomes else if.

Comparing with ===

SignMeaning
===is equal
!==is not equal
<, >, <=, >=smaller, bigger …

JavaScript also has == with two signs – but that secretly converts types, and suddenly "5" == 5 is true. That’s why professionals always use ===:

console.log(5 === 5);
console.log("5" === 5);
console.log("5" == 5);   // careful: true!

Combining conditions

&& means and, || means or, ! means not:

const age = 13;
const hasTicket = true;

if (age >= 12 && hasTicket) {
  console.log("Enjoy the film!");
}
if (age < 6 || age > 65) {
  console.log("Discount!");
} else {
  console.log("Normal price.");
}
console.log(!hasTicket);

Quick check

What does this program print?

const a = 7;
if (a > 10 || a % 2 === 1) {
  console.log("yes");
} else {
  console.log("no");
}

Your task

Your turn

Write the function rating(points). It returns "great" if there are at least 90 points, "good" from 50 points and "practise" otherwise.

function rating(points) {
  // Return "great", "good" or "practise"
}

console.log(rating(95));
console.log(rating(60));
console.log(rating(10));

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

function rating(points) {
  if (points >= 90) {
    return "great";
  } else if (points >= 50) {
    return "good";
  } else {
    return "practise";
  }
}

console.log(rating(95));
console.log(rating(60));
console.log(rating(10));