Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
else if
course content

Course Content

Introduction to JavaScript

else ifelse if

Now, let's explore a scenario where multiple conditions come into play:

In this example, the variable a is greater than 10, but other messages like "greater than 5" and "greater than 0" are also being printed. This isn't the desired behavior when you want to execute only one condition. The else statement wouldn't work well here due to multiple conditions.

Introducing else if

The else if construct provides a solution for selecting a specific code block within a series of conditions:

As you can see, the else-if statement is straightforward, with an if statement followed by it:

Let's apply this to our example:

Now, we've created a sequence of conditions. When at least one if condition becomes true, the chain is interrupted.

Note

This structure is useful when you only need one condition to be satisfied.

Adding else

You can also add an else statement after the condition chain. Let's modify our example:

Everything was clear?

Section 4. Chapter 3
some-alt