Lessons / JavaScript / Unit 2

Making decisions

Programs need to do different things in different situations. You do that by comparing values and running some code only when the comparison is true.

JavaScript · Unit 2 of 5 · about 4 minutes

true and false

A comparison gives back one of two values: true or false. These are called booleans.

console.log(5 > 3);
console.log(5 < 3);
console.log(4 === 4);
console.log(4 !== 4);
true
false
true
false

=== checks if two values are the same. !== checks if they are different. You'll also see <= (less than or equal) and >= (greater than or equal).

Try it

What does this print?

console.log(3 === "3");
=== checks the type too. One side is a number and the other is a string, so they are not the same.

if

if runs the code inside its curly braces only when the condition in the brackets is true.

let temp = 30;

if (temp > 25) {
  console.log("It's hot");
}
console.log("Done");
It's hot
Done

If temp were 20, the first message would be skipped and only Done would print.

else and else if

else runs when the condition was false. else if lets you check another condition. JavaScript checks them from the top and runs the first one that's true, then skips the rest.

let score = 72;

if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("Keep practising");
}
B

Try it

What does this print?

let n = 7;

if (n > 10) {
  console.log("big");
} else if (n > 5) {
  console.log("medium");
} else {
  console.log("small");
}
7 is not greater than 10, so the first block is skipped. 7 is greater than 5, so medium prints and the rest is skipped.

Combining conditions

&& means and: both sides must be true. || means or: at least one side must be true. ! flips true to false and false to true.

let age = 15;
let hasTicket = true;

if (age >= 13 && hasTicket) {
  console.log("You can go in");
}
You can go in

Try it

What does this print?

let a = true;
let b = false;
console.log(a && b);
&& needs both sides to be true. b is false, so the whole thing is false.

Common mistakes

Using = instead of ===

if (x = 5) stores 5 in x instead of comparing. The condition is then always treated as true. Use === to compare.

Using == instead of ===

== tries to convert types before comparing, so 3 == "3" is true. That causes surprises. Stick with ===.

Putting the most general check first

If you check score >= 50 before score >= 90, a score of 95 matches the first one and never reaches the second. Put the strictest check at the top.

Recap

  • Comparisons give true or false.
  • if runs code only when its condition is true.
  • else if and else handle the other cases. Only one block runs.
  • && means and, || means or, ! means not.