Code Highlights logo

Learn

Conditional Statements

Else If Statements

In programming, there are situations where we need to evaluate multiple conditions and execute different blocks of code depending on the outcome. The if statement alone might not always be sufficient for these scenarios. In such cases, we can make use of the else if statement to handle additional conditions.

The else if statement allows us to chain multiple conditions together and provides an alternative block of code to be executed if the previous condition(s) evaluate to false. This allows for more flexibility in our program's logic.

Let's take a look at the syntax of the else if statement:

1if (condition1) {
2 // code to be executed if condition1 is true
3} else if (condition2) {
4 // code to be executed if condition1 is false and condition2 is true
5} else if (condition3) {
6 // code to be executed if condition1 and condition2 are false and condition3 is true
7} else {
8 // code to be executed if all conditions are false
9}

It's important to note that else if statements are evaluated in order from top to bottom. Once a condition evaluates to true, the corresponding block of code is executed and the rest of the else if statements are skipped. If none of the conditions evaluate to true, the code within the else block is executed as a fallback.

Example: Let's say we are building a program that determines the grade of a student based on their score. We can use else if statements to handle different score ranges and assign the corresponding grade:

1let score = 85;
2let grade;
3
4if (score >= 90) {
5 grade = 'A';
6} else if (score >= 80) {
7 grade = 'B';
8} else if (score >= 70) {
9 grade = 'C';
10} else if (score >= 60) {
11 grade = 'D';
12} else {
13 grade = 'F';
14}
15
16console.log(`Your grade is ${grade}`);

In this example, the program checks the score against different conditions and assigns the appropriate grade based on the score. If the score is 85, the output would be "Your grade is B".


Instructions

1.

Add an else if statement that checks if num is greater than 10.

2.

If num is greater than 10, assign the string "Large number" to a variable named result.

3.

Else if num is greater than 5, assign the string "Medium number" to a variable named result

4.

Else, assign the string "Small number" to a variable named result

5.

Print the value of result to the console.

Sign up to start coding

Already have an account?

Sign In

Course content