BeginnerLesson 5 of 305 min read

Conditions: if, else, switch and the ternary operator

Make programs decide: if / else if / else, truthy and falsy values, the ternary operator and switch statements.

In this lesson you will

  • Write if, else if and else
  • Understand truthy and falsy values
  • Use the ternary operator
  • Choose between options with switch

About 16 minutes

Crossroads in code

You walk to the door of a cafe. If it is open, you go in. Otherwise you walk on. Every day you make hundreds of decisions like this. Programs need to do the same: show a welcome message only to logged-in users, accept a password only if it is long enough, give a discount only above a certain total. The tool for all of these is the conditional.

if, else if, else

const hour = 14;

if (hour < 12) {
  console.log("Good morning");
} else if (hour < 18) {
  console.log("Good afternoon");
} else {
  console.log("Good evening");
}

Read it top to bottom. JavaScript checks the first condition in the brackets. If it is true, it runs that block and skips the rest. If not, it moves to the next else if. The final else catches everything that did not match. Only one block ever runs.

Good to know

The code inside curly braces { } is a block. Indent it by two or four spaces. Indentation does not matter to the computer but matters hugely to humans reading your code.

Write a grade checker: 90 or more prints A, 75 or more prints B, 50 or more prints C, otherwise prints Fail. Try changing the score.

const score = 82;
// add if / else if / else

Start with the highest threshold first, because the first true condition wins.

const score = 82;
if (score >= 90) {
  console.log("A");
} else if (score >= 75) {
  console.log("B");
} else if (score >= 50) {
  console.log("C");
} else {
  console.log("Fail");
}

Combining conditions

const age = 17;
const hasParent = true;

if (age >= 18 || hasParent) {
  console.log("You can enter");
} else {
  console.log("Sorry");
}

if (!(age >= 18)) {
  console.log("Under 18");
}

Truthy and falsy

JavaScript can treat any value as if it were true or false inside a condition. Exactly six values count as falsy: false, 0, "" (empty text), null, undefined and NaN. Everything else is truthy, including "0", "false" and empty arrays.

const username = "";

if (username) {
  console.log("Welcome " + username);
} else {
  console.log("Please enter a name");   // runs: empty text is falsy
}

The ternary operator: a one-line decision

const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status);   // adult

console.log(`You have ${3} ${3 === 1 ? "item" : "items"}`);

The ternary is a compact if/else that produces a value. Use it for simple choices. For anything longer, a regular if is easier to read.

switch: many exact matches

const day = "Tue";

switch (day) {
  case "Mon":
    console.log("Start of week");
    break;
  case "Fri":
    console.log("Almost weekend");
    break;
  case "Sat":
  case "Sun":
    console.log("Weekend");
    break;
  default:
    console.log("Regular day");
}

switch compares one value against many exact options. The break keyword stops the switch from “falling through” into the next case. Two cases stacked together (like Sat and Sun) share one result. The default case is the fallback, like else.

Write a switch for a traffic light colour. red prints Stop, yellow prints Get ready, green prints Go, anything else prints Broken light.

const light = "green";
// write the switch

Use case “red”: … break; and a default at the end.

const light = "green";
switch (light) {
  case "red":
    console.log("Stop");
    break;
  case "yellow":
    console.log("Get ready");
    break;
  case "green":
    console.log("Go");
    break;
  default:
    console.log("Broken light");
}

Real example: a shipping rule

const total = 1800;
const isMember = true;

let shipping;
if (total >= 2000) {
  shipping = 0;
} else if (isMember) {
  shipping = 100;
} else {
  shipping = 250;
}

console.log(`Shipping: Rs ${shipping}`);

Notice how the code mirrors the business rule in plain words: free over 2000, cheaper for members, standard otherwise. When you can say a rule out loud, you can write it as an if.

Common mistake

Putting a semicolon right after the condition: if (x > 5);. That ends the if with an empty block, and the following braces always run. Another frequent slip is forgetting break in a switch.

Early exit keeps code flat

Instead of nesting if inside if inside if, handle the bad case first and stop. This style, called a guard clause, is easier to read and you will use it with functions.

Worked example: login checker

Here is a fuller decision problem. A site accepts a login when the username is not empty, the password is at least eight characters, and the account is not locked. Each failure should give a specific message, which is much kinder to users than “Something is wrong”.

function checkLogin(username, password, locked) {
  if (!username) return "Please enter a username";
  if (password.length < 8) return "Password needs 8 or more characters";
  if (locked) return "Account locked. Try again later";
  return "Welcome back, " + username;
}

console.log(checkLogin("", "secret123", false));
console.log(checkLogin("sara", "abc", false));
console.log(checkLogin("sara", "secret123", true));
console.log(checkLogin("sara", "secret123", false));

Notice there is no else anywhere. Each return ends the function, so reaching a later line means all earlier checks passed. This style stays flat and readable however many rules you add.

Add one more rule: usernames shorter than 3 characters should return “Username too short”. Decide where it belongs and test it.

function checkLogin(username, password) {
  if (!username) return "Please enter a username";
  if (password.length < 8) return "Password too short";
  return "Welcome " + username;
}
console.log(checkLogin("ab", "secret123"));

Put it right after the empty check, using username.length < 3.

function checkLogin(username, password) {
  if (!username) return "Please enter a username";
  if (username.length < 3) return "Username too short";
  if (password.length < 8) return "Password too short";
  return "Welcome " + username;
}
console.log(checkLogin("ab", "secret123"));

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

How many blocks run in an if / else if / else chain?

  1. All of them
  2. Exactly one
  3. Two
  4. None

Only the first matching block runs.

Which value is falsy?

  1. "0"
  2. []
  3. 0
  4. "false"

The number 0 is falsy; the others are truthy.

What does 5 > 3 ? "yes" : "no" return?

  1. “no”
  2. “yes”
  3. true
  4. error

The condition is true, so the first value is used.

What is break for in a switch?

  1. Ends the program
  2. Stops the switch falling through to the next case
  3. Creates a loop
  4. Skips the default

Without it, execution continues into the next case.

What is wrong with if (x = 5)?

  1. Nothing
  2. It assigns instead of comparing
  3. It needs else
  4. It is too short

= assigns; use === to compare.

Summary

  • if / else if / else runs one block.
  • Six falsy values: false, 0, empty text, null, undefined, NaN.
  • The ternary is a short if/else for values.
  • switch compares one value to many cases and needs break.

Next lesson

Next: loops, repeating work without repeating code.

Questions

Should I use switch or if?

Use switch for one value against many exact matches, if for ranges and complex conditions.

Do I need curly braces for a one-line if?

They are optional but recommended. They prevent bugs when you add a second line later.

What does else if do if the first condition is true?

It is skipped entirely. Only the first true branch runs.

Progress is saved in this browser.