if, else and comparing things

Programs get interesting when they can make decisions. if runs a block of code only when a condition is true:

const age = 15;
if (age >= 13) {
  console.log("You can make an account");
} else {
  console.log("Come back in a few years");
}

The condition goes in round brackets, the code to run goes in curly brackets. else is the "otherwise" branch. Need more than two options? Chain them with else if, and JavaScript runs the first branch whose condition is true, then skips the rest:

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

Comparisons

  • > < >= <=: bigger, smaller, and "or equal"
  • ===: equal
  • !==: not equal

Each one gives back a boolean, true or false.

Notice there are three equals signs. A single = assigns a value, it does not compare. And == (two signs) does exist, but it converts types before comparing, so "5" == 5 is true. That sounds helpful until it creates bugs that take an evening to find. === checks the type too, so "5" === 5 is false. Use === and !==, always.

If you have a string that should be a number (text from a form, for example), convert it on purpose with Number("5").

You can combine conditions: && means "and" (both must be true), || means "or" (at least one), and ! flips true and false.

Try it yourself

Edit it. Break it. Run it again.
const temp = 24;
if (temp >= 30) {
  console.log("Hot");
} else if (temp >= 15) {
  console.log("Nice");
} else {
  console.log("Cold");
}

console.log("5" == 5);
console.log("5" === 5);
console.log(Number("5") === 5);
console.log(temp > 20 && temp < 30);
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Weather report

Using temp, print Hot if it is 30 or more, Nice if it is 15 or more, and Cold otherwise. With temp set to 22, your program should print Nice.

const temp = 22;
if (temp >= 30) {
  console.log("Hot");
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Strings are not numbers

input is a string, so the comparison fails and the code prints no match. Without changing the first line or using ==, make it print match.

const input = "5";
if (input === 5) {
  console.log("match");
} else {
  console.log("no match");
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.