Conditions — JavaScript

if (condition) { ... } else if (another condition) { ... } else { ... } runs only one branch (one { } block): the first one whose condition is true, or else…

So far, every line of your code always runs, top to bottom. A report card program can't work like that. A score of 80 should get "Pass", a score of 60 should get "Not Passed", and only one of them should be printed.

For that you need a condition: a rule that runs one piece of code if something is true, and another piece if it is false. In JavaScript, you write a condition with if and else (otherwise). It has the same shape as the sentence "if it rains, take an umbrella, otherwise wear a hat".

if, else if, else

This example prints one of three report card results, depending on the score:

let score = 80;

if (score >= 90) {
  console.log("A: excellent");
} else if (score >= 75) {
  console.log("B: pass");
} else {
  console.log("C: not passed");
}

With a score of 80, the first condition is false and the second is true. So B: pass is printed, and else is skipped. JavaScript checks the conditions from top to bottom and stops at the first one that is true. That is why the strictest condition (the biggest number) goes at the top. If score >= 75 came first, a score of 95 would stop there and only get a B.

else if and else are optional. An if on its own is fine too.

Comparison operators

You build a condition with a comparison operator. Each line below prints the result of one comparison:

console.log(75 > 75);   // false
console.log(75 >= 75);  // true
console.log(5 === 5);   // true
console.log("5" === 5); // false
console.log(5 !== 3);   // true

Suppose the condition for passing is score > 75 and your score is exactly 75. You don't pass, because 75 > 75 is false. If a score of 75 should pass, use >=.

=== checks the value and the type at once. "5" (text) and 5 (a number) are different types, so in the example above the result is false. In the same way, "" === false is false: empty text and false are different types.

There is also ==, with two equals signs. == converts the types first and then compares, so "5" == 5 is true. The results of == often surprise people, so make === your habit. A single = is different again: it puts a value into a variable, and it does not compare.

Joining two conditions. && (and) gives true only when both conditions are true. || (or) needs only one of them to be true.

const score = 80;
const attended = 12;
console.log(score >= 75 && attended >= 14); // false
console.log(score >= 75 || attended >= 14); // true

For example, to pass, a student needs a score of at least 75 and at least 14 classes attended. A score of 80 meets the first condition, but 12 classes are not enough. So && gives false, while || gives true.

Conditions inside a function

The function below uses if to choose which text it returns:

function checkAge(age) {
  if (age >= 17) {
    return "Can get an ID card";
  }
  return "Not allowed yet";
}

console.log(checkAge(20)); // Can get an ID card
console.log(checkAge(12)); // Not allowed yet

return gives back the result and stops the function right away. So the line return "Not allowed yet" is only reached when the if condition above it is false. In the exercise, the text you return has to be exactly what is asked for: "Pass" and "pass" are two different texts.

Ternary: if-else on one line

When you only choose one of two values, there is a shorter form, called the ternary:

const score = 80;
const status = score >= 75 ? "Pass" : "Not Passed";
console.log(status); // Pass

The shape is condition ? valueIfTrue : valueIfFalse. A ? goes after the condition, and a : goes between the two choices. In the example, the condition score >= 75 is true, so the first choice, "Pass", is picked.

Other options for choosing a branch:

Form When to use it
if / else if / else The form this lesson uses, because it can check a range of numbers such as score >= 75.
switch Comparing one value with many fixed values, such as the name of a day.

A switch that checks the name of a day:

const day = "Sunday";
switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Shop closed");
    break;
  default:
    console.log("Shop open");
}
// Shop closed

switch compares day with each case using ===. case "Saturday": and case "Sunday": are stacked with no code between them, so they share the same code. default runs when nothing matches. break ends the switch. Without break, the code of the next case runs too.

⚠️ A semicolon, a return and an else that break a condition

TL;DR: if (condition) { ... } else if (another condition) { ... } else { ... } runs only one branch (one { } block): the first one whose condition is true, or else when none is true. That is why the strictest condition goes on top. >= and <= include the boundary number (75 passes score >= 75), > and < don't. Compare with ===, because === checks both the value and the type. Inside a function, give back the result with return. To choose one of two values, use the ternary condition ? a : b: it gives a when the condition is true and b when it is false.

⚡ Only one branch runs

Write:

if (score >= 90) {
  console.log("A: excellent");
} else if (score >= 75) {
  console.log("B: pass");
} else {
  console.log("C: not passed");
}
Guess first: if score >= 75 came first, what would a score of 95 get?

Only a B. JavaScript stops at the first condition that is true, and 95 already passes score >= 75. The condition for an A is never checked.

Meaning: if checks the condition inside the parentheses. If it is true, the code inside its { } runs. If it is false, JavaScript moves down to the next condition. else has no condition: its code runs when every condition above it is false. Put the strictest condition at the top.

⚡ >= includes the boundary

Write:

console.log(75 > 75);  // false
console.log(75 >= 75); // true

Meaning: > (greater than) and < (less than) leave the boundary number out, here 75. >= and <= include it. If a score of exactly 75 should pass, use >=.

⚡ Compare with ===

Write:

console.log(5 === 5);   // true
console.log("5" === 5); // false
Guess first: what does "5" == 5, with two equals signs, give?

true. == converts the types first and then compares, so the text "5" counts as equal to the number 5. The results of == often surprise people, so make === your habit.

Meaning: === checks the value and the type at once. "5" is text and 5 is a number, so the second line prints false. A single = is different again: it puts a value into a variable, and it does not compare.

What you will learn