Understanding if/else statements

Published:

Let’s say you’re walking on a busy street in the middle of town. You’re about to cross the road when you notice the traffic light for pedestrians turns red. What do you do?

You stop, don’t you?

And what happens when the light turns green again? You start walking.

We can put this analogy into code too. It sounds something like: “If the light turns red, stop walking. Otherwise, continue walking”.

And that, my friend, is the foundation of an if/else statement.

The if/else statement

The if/else statement helps to control what your program does in specified situations. It looks like this:

if (condition) {
  // Do something
} else {
  // Do some other thing
}

The condition tells JavaScript what to check for before continuing. If the condition evaluates to true, JavaScript executes the code within the if block.

If the condition evaluates to false, JavaScript executes code from the else block.

In the traffic light example, we check whether the light is red:

// Note: This example doesn't contain valid code yet
if (light is red) {
  // stop walking
} else {
  // continue walking
}

If you need to check for more than one condition, you can use else if, which goes between if and else.

When would you need such a second condition?

Well, let’s say you want to cross a small road. If there aren’t any cars around, would you wait for the traffic light to turn green? You still cross, don’t you?

In code, this would look like:

if (light is red) {
  // Stop walking
} else if (cars around) {
  // Stop walking
} else if (police around) {
  // Stop walking
} else {
  // Continue walking
}

In this case, if the first condition evaluates to true, JavaScript executes the code in the if block.

If the first condition evaluates to false, JavaScript checks the condition in the next else if block and see whether it evaluates to true. It goes on and on until all else if blocks are exhausted.

To check whether a condition evaluates to true or false, JavaScript relies two things:

  1. Comparison operators
  2. Truthy and falsey values

Let’s talk about comparison operators first.

Comparison operators

There are four main types of comparison operators:

  1. Greater than (>) or greater or equals to (>=)
  2. Smaller than (<) or smaller or equals to (<=)
  3. Strictly equal (===) or equal (==)
  4. Strictly unequal (!==) or unequal (!=)

The first two types of comparison operators are straightforward. You use them to compare numbers.

24 > 23 // True
24 > 24 // False
24 >= 24 // True

24 < 25 // True
24 < 24 // False
24 <= 24 // True

The next two types of comparison operators are quite straightforward as well. You use them to check whether things are equal or unequal to each other.

24 === 24 // True
24 !== 24 // False

However, there’s a difference between strictly equal (===) vs equal (==), and strictly unequal (!==) vs unequal (!=):

'24' === 24 // False
'24' == 24 // True

'24' !== 24 // True
'24' != 24 // False

As you can see from the example above, when you compare a string of 24 vs the number 24, === evaluates to false while == evaluates to true.

Why is this so? Let’s look at the difference between strictly equal and equal

=== vs == (or !== vs !=)

JavaScript is a loosely-typed language. What this means is that, when we declare variables, we don’t care what type of value goes into the variable.

You can declare any primitive or object, and JavaScript does the rest for you automatically:

const aString = 'Some string'
const aNumber = 123
const aBoolean = true

When comparing things with strictly equal (===) or strictly unequal (!==), JavaScript checks the type of variable. This is why a string of 24 and a number 24 do not equate.

'24' === 24 // False
'24' !== 24 // True

When comparing things with equal (==) or unequal (!=), JavaScript converts (or casts) the types so they match each other.

Generally, JavaScript tries to convert all types to numbers when you use a conversion operator. In the example below, the string 24 is converted into the number 24 before the comparison.

That’s why a string of 24 equates to a number of 24 when you use ==.

'24' == 24 // True
'24' != 24 // False

Booleans can also be converted into numbers. When JavaScript converts Booleans into numbers, true becomes 1 and false becomes 0.

0 == false // True
1 == true // True
2 == true // False

Automatic type conversion (when using comparison operators) is one of the common causes of hard-to-find bugs. Whenever you compare for equality, always use the strict versions (=== or !==).

Comparing objects and arrays

Try comparing objects and arrays with === or ==. You’ll be very surprised.

const a = { isHavingFun: true }
const b = { isHavingFun: true }

console.log(a === b) // false
console.log(a == b) // false

In the example above, both a and b look exactly the same. They are both objects, they have the same values.

The strange thing is, a === b is always going to be false. Why?

Let’s say you have an identical twin brother/sister. You look exactly the same as your twin. Same hair color, same face, same clothes, same everything. How can people differentiate the two of you? It’ll be hard.

In JavaScript, each object has a “identity card”. This identity card is called the reference to the object. When you compare objects with equality operators, you’re asking JavaScript to check if the two objects have the same reference (same identity card).

Is it a surprise that a === b is always going to be false now?

Let’s tweak it a little and assign a to b.

const a = { isHavingFun: true }
const b = a

In this case, a === b evaluates to true because b now points to the same reference as a.

console.log(a === b) // true

Truthy and Falsey

If you write a single variable (like hasApples in the example below) as the condition of an if/else statement, JavaScript checks for a truthy or a falsey value.

const hasApples = 'true'
if (hasApples) {
  // Eat apple
} else {
  // Buy apples
}

A falsey value is a value that evaluates to false when converted into a boolean. There are six possible falsey values in JavaScript:

  1. false
  2. undefined
  3. null
  4. 0 (numeric zero)
  5. "" (empty string)
  6. NaN (Not A Number)

A truthy value, on the other hand, is a value that evaluates to true when converted into a Boolean. In the case of numbers, anything that’s not 0 converts to true.

Automatic type conversion to truthy and falsey values are highly encouraged in JavaScript, because they make code shorter and easier to comprehend.

For example, if you want to check if a string is empty, you can use the string in the condition straightaway.

const str = ''

if (str) {
  // Do something if string is not empty
} else {
  // Do something if string is empty
}

Wrapping up

if/else statements are used to control what your program does in specific situations. It lets you determine whether to walk or cross the road, depending on the conditions given to you.

To check if a condition is true or false, Javascript relies on two things:

  1. comparison operators
  2. truthy/false values

If you loved this article, you’ll love learn Learn JavaScript—a course that helps you learn to build real components from scratch with Javascript. Click here to find out more about Learn JavaScript if you’re interested.

Here's how to become great at JavaScript in less than 2 months

If you’re stuck because of your lack of JavaScript skills, you can stop worrying now.

We’ll help you become amazing at JavaScript — we have a course that can help you understand and use JavaScript easily.

And we’re going to give you three chapters for free because we love to help developers become superheroes.

Just click the button below to become an amazing JavaScript developer.