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

Conteúdo do Curso

Introduction to JavaScript

Introduction to JavaScript

1. Basic Concepts
2. Variables and Data Types
3. Basic Operations
4. Conditional Statements
5. Loops
6. Functions

bookelse if

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

1234567891011121314151617
let a = 11; if (a > 15) { console.log('greater than 15'); } if (a > 10) { console.log('greater than 10'); } if (a > 5) { console.log('greater than 5'); } if (a > 0) { console.log('greater than 0'); }
copy

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:

1234567891011
let a = 11; if (a > 15) { console.log("greater than 15"); } else if (a > 10) { console.log("greater than 10"); } else if (a > 5) { console.log("greater than 5"); } else if (a > 0) { console.log("greater than 0"); }
copy

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:

12345678910111213
let a = -61; if (a > 15) { console.log("greater than 15"); } else if (a > 10) { console.log("greater than 10"); } else if (a > 5) { console.log("greater than 5"); } else if (a > 0) { console.log("greater than 0"); } else { console.log("No condition is satisfied"); }
copy

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 3
some-alt