The JavaScript if/else conditional

By

Published · Updated

Tagged: JavaScript

Learn how the JavaScript if/else conditional works: truthy and falsy values, else if chains, combining conditions, the = vs === mistake, early returns, and when to use a ternary.

An if statement is used to make the program take a route, or another, depending on the result of an expression evaluation.

This is the simplest example, which always executes:

if (true) {
  //do something
}

on the contrary, this is never executed:

if (false) {
  //do something (never)
}

In real code you put an expression between the parentheses, like a comparison:

const age = 20

if (age >= 18) {
  console.log('You can vote')
}

If you have a single statement to execute after the conditionals, you can omit the block, and just write the statement:

if (true) doSomething()

Be careful with this. If you later add a second line, only the first one is part of the if:

if (loggedIn)
  showDashboard()
  loadNotifications() // this always runs!

I always use the braces, even for one line. You also can’t declare a variable with let or const without braces. if (ok) let x = 1 is a SyntaxError.

Truthy and falsy values

The conditional checks the expression you pass to it for true or false value. If you pass a number, that always evaluates to true unless it’s 0. If you pass a string, it always evaluates to true unless it’s an empty string. Those are general rules of casting types to a boolean.

Here’s the full list of values that count as false. They’re called falsy:

Everything else is truthy, including some values that look like they should be false:

if ([]) {}               // runs: an empty array is truthy
if ({}) {}               // runs: an empty object is truthy
if ('0') {}              // runs: a non-empty string
if ('false') {}          // runs: a non-empty string
if (new Boolean(false)) {} // runs: it's an object

The empty array one bites a lot of people. To check if an array has items, check its length:

if (items.length > 0) {
  // there's at least one item
}

And to check if an object has properties, use Object.keys(obj).length > 0.

Else

You can provide a second part to the if statement: else.

You attach a statement that is going to be executed if the if condition is false:

if (true) {
  //do something
} else {
  //do something else
}

Else if

Since else accepts a statement, you can nest another if/else statement inside it:

if (a === true) {
  //do something
} else if (b === true) {
  //do something else
} else {
  //fallback
}

There’s no special elseif keyword in JavaScript, like in PHP. else if is just an else followed by another if.

The conditions are checked from top to bottom, and only the first one that’s true runs. So put the most specific check first:

const score = 95

if (score >= 90) {
  console.log('A')
} else if (score >= 80) {
  console.log('B')
} else {
  console.log('C or lower')
}
// A

If you swapped the first two checks, a score of 95 would print B, because 95 >= 80 is true and the check stops there.

When you have many else if comparing the same value against fixed options, a switch is often easier to read.

Combining conditions

Use && (and), || (or) and ! (not) to check more than one thing at once:

if (age >= 18 && hasTicket) {
  console.log('Come in')
}

if (isAdmin || isOwner) {
  console.log('You can edit this')
}

if (!loggedIn) {
  console.log('Please log in')
}

Use parentheses when you mix && and ||, so you (and whoever reads the code) don’t have to remember which one goes first:

if ((isAdmin || isOwner) && !isLocked) {
  // ...
}

The = vs === mistake

= assigns a value, === compares. This is a classic bug:

let x = 0

if (x = 5) {
  console.log('this always runs')
}
// x is now 5

x = 5 sets x to 5, and the result of the assignment is 5, which is truthy. So the block always runs and you’ve changed x too.

Use === to compare. Prefer it over ==, which converts types before comparing and gives surprising results like '0' == false being true.

Return early instead of nesting

When a function has several checks, nested if blocks get hard to follow:

function checkout(user, cart) {
  if (user) {
    if (cart.length > 0) {
      // do the checkout
    }
  }
}

Check the failure cases first and exit with return:

function checkout(user, cart) {
  if (!user) return
  if (cart.length === 0) return

  // do the checkout
}

The main code isn’t indented inside two blocks anymore, and each condition is easy to read on its own.

A shorter form: the ternary operator

When you just want to pick one of two values, the ternary operator does it in one line:

const label = age >= 18 ? 'adult' : 'minor'

This is the same as:

let label
if (age >= 18) {
  label = 'adult'
} else {
  label = 'minor'
}

The ternary is an expression, so it returns a value and you can use it where if doesn’t fit, like inside a template literal or in JSX. For anything with more than one line of code in each branch, stick with if/else.

Want me to talk about your product? You can sponsor this site.

Related posts about js: