JavaScript Basics: Make Web Pages Come Alive · Lesson 3 of 8

Lesson 3: Comparisons and Decisions with if/else

Compare values, combine conditions, and make your code choose using if, else if and else.

Lesson 3: Comparisons and Decisions with if/else

Comparing values

Comparisons give true or false. Always prefer === (strictly equal) and !== over the looser ==, which converts types and can surprise you.

console.log(5 > 3);
console.log(5 === 5);
console.log(5 === "5");
console.log(5 == "5");
console.log(7 !== 8);

Output:

true
true
false
true
true

if, else if, else

const marks = 66;
if (marks >= 80) {
  console.log("Distinction");
} else if (marks >= 60) {
  console.log("First division");
} else if (marks >= 40) {
  console.log("Pass");
} else {
  console.log("Fail");
}

Output:

First division

The condition goes in round brackets, and the code to run goes in curly brackets { }.

Combining conditions

OperatorMeaning
&&and: both must be true
||or: at least one is true
!not: flips true/false
const age = 17;
const hasCard = true;
console.log(age >= 16 && hasCard);
console.log(age < 10 || hasCard);
console.log(!hasCard);

Output:

true
true
false

A short form: the ternary

const n = 7;
console.log(n % 2 === 0 ? "even" : "odd");

Output:

odd

Truthy and falsy

Besides false, these count as false in a condition: 0, "" (empty text), null, undefined and NaN. Everything else counts as true.

const name = "";
if (name) {
  console.log("Hello " + name);
} else {
  console.log("Please enter your name");
}

Output:

Please enter your name

Try it yourself

  1. Print whether a number is positive, negative or zero.
  2. Print a message if someone is at least 18 and has a citizenship card.
  3. Rewrite your answer to 1 using the ternary operator.

Next lesson: loops.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 3: Comparisons and Decisions with if/else | MeroSir