Conditionals

Topic 2 of 5 in Operators & control flow7 min readBeginnerFree course

Overview

Programs need to make decisions: show an error if a form field is empty, offer a discount if the basket is big enough, say good morning or good evening. An if statement runs a block of code only when its condition is true.

JavaScript
const temperature = 31;

if (temperature > 30) {
  console.log('It’s hot today.');
}

The part in brackets is the condition. It can be any expression; JavaScript evaluates it and, if the result is truthy, runs the block in curly braces. Otherwise the block is skipped and the program carries on after it.

else

Add an else block to run code when the condition is false. Exactly one of the two blocks runs:

JavaScript
const age = 16;

if (age >= 18) {
  console.log('You can vote.');
} else {
  console.log(`You can vote in ${18 - age} years.`);
}

else if

For more than two outcomes, chain conditions with else if:

JavaScript
const hour = 14;

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

JavaScript checks each condition in order and runs the first block that matches. The rest are skipped — even if their conditions would also be true.

For hour = 14: hour < 12 is false so that branch is skipped; hour < 18 is true so ‘Good afternoon’ runs, and the else branch is never reached.

Order matters

Because the first match wins, put the most specific conditions first. This version has a bug:

JavaScript
if (score >= 50) {
  grade = 'C';
} else if (score >= 90) {
  grade = 'A'; // never reached — 95 already matched >= 50
}

Checking from highest to lowest fixes it.

Combining conditions

Use logical operators to build richer conditions:

JavaScript
if (age >= 18 && hasTicket) {
  console.log('Welcome in!');
}

if (day === 'Sat' || day === 'Sun') {
  console.log('Weekend!');
}

if (!isLoggedIn) {
  showLoginButton();
}

When a condition gets long, give it a name. The if then reads like a sentence:

JavaScript
const isWeekend = day === 'Sat' || day === 'Sun';
const canBook = isMember && seatsLeft > 0 && !isWeekend;

if (canBook) {
  book();
}

To check a value against a list, includes is shorter than many ||:

JavaScript
if (['Sat', 'Sun'].includes(day)) { /* weekend */ }

Truthy and falsy conditions

The condition doesn’t have to be a boolean. These values count as false: false, 0, '', null, undefined and NaN. Everything else counts as true.

JavaScript
const name = '';
if (!name) {
  console.log('Please enter your name.');
}

const items = [];
if (items.length) {
  console.log('You have items'); // skipped: length is 0, which is falsy
}

Be careful when 0 is valid. if (quantity) is false for 0, which might be a perfectly good quantity. Write exactly what you mean: if (quantity !== undefined) or if (quantity > 0).

Nesting

Blocks can contain other if statements:

JavaScript
if (user) {
  if (user.isAdmin) {
    showAdminPanel();
  } else {
    showDashboard();
  }
}

A little nesting is fine, but deep nesting — sometimes called the “arrow” or “pyramid” shape — makes code hard to follow. The next technique flattens it.

Early returns

Inside functions, returning as soon as you know the answer avoids deep nesting. These checks at the top of a function are called guard clauses:

JavaScript
// Nested
function canEnroll(user) {
  if (user) {
    if (user.verified) {
      return user.age >= 13;
    }
  }
  return false;
}

// Flat, with guard clauses
function canEnroll(user) {
  if (!user) return false;
  if (!user.verified) return false;
  return user.age >= 13;
}

Both do the same thing, but in the second version each rule is on its own line, and the “happy path” is at the bottom with no indentation.

Choosing a value: the ternary

When you only need to pick between two values, the ternary operator is shorter than an if…else:

JavaScript
// if…else
let message;
if (isMember) {
  message = 'Welcome back';
} else {
  message = 'Sign up today';
}

// ternary
const message = isMember ? 'Welcome back' : 'Sign up today';

Use if when you need to do things (run several statements); use the ternary when you need to choose a value.

Braces

If a block has only one statement, the braces are optional:

JavaScript
if (isDone) console.log('Finished');

That’s fine for one-line guard clauses, but always use braces for anything longer. Without them, only the first statement belongs to the if, and adding a second line later is a classic bug:

JavaScript
if (isDone)
  console.log('Finished');
  celebrate(); // always runs — it's not part of the if!

Keep conditions readable. If a condition gets long, give it a name: const isWeekend = day === 'Sat' || day === 'Sun';

Exercise

Grade a score

Write grade(score) that returns 'A' for 90+, 'B' for 75+, 'C' for 50+, and 'Try again' otherwise. Return 'Invalid' if the score is below 0 or above 100.

JavaScript
function grade(score) {
  // your code here
}

grade(95);  // 'A'
grade(60);  // 'C'
grade(120); // 'Invalid'

Summary

  • if runs a block only when its condition is truthy.
  • Chain checks with else if; the first match wins, so order matters.
  • Combine conditions with && and ||; name long conditions with a const.
  • Returning early (guard clauses) keeps functions flat and readable.
  • Use the ternary operator when you just need to choose between two values.