JavaScript if, else, and else if Statement
Overview
Conditional statements are used through the various programming languages to instruct the computer on the decision to make when given some conditions. These decisions are made if the pre-stated conditions are either true or false, depending on the functions the programmer has in mind.
The if else statement can be used in situations where we have to make decisions depending on the existence of a particular condition. The else statement is not mandatory and will execute only if the if condition fails. The if else statement can be nested or chained using multiple conditions.
Introduction to if else in JavaScript
Remember those autumn mornings during school time? Heavy rains and you have to decide whether you're going to school or not? Well, the usual answer used to be If it stops raining, then I'll go the school; otherwise, I won't.
In programming, we often encounter situations where we are given two (or more) choices, and we have to proceed with one. In such cases, an if else statement comes handy. Because of this behavior, the if else statement is also known as the conditional statement.
For e.g. When you log into a social media site, it asks for your username and password, and then it matches both with the ones stored in its database. Now imagine it has found your username, and now it is matching the user-entered password with the one in its database (note: it would start matching the password only if the first condition is true; otherwise, it will execute the else block). If the password matches, it will proceed to open your account, else it will prompt that the password is wrong.
This is one of the many examples where the if-else statement comes in handy.
How to Use Conditional Statements?
If else statements are also known as conditional statements. This is so because of their property of executing a certain process only if a certain condition is satisfied.
In order to use an if-else statement, we need to follow a set of steps:
Define a condition.
- First of all, we need to define a condition. The conditional could be any statement that would return a true or false value. For e.g. it can be the comparison of two operands using comparison operators or a simple boolean variable.
Place the condition inside if() Statement
- Once the condition is defined, place the condition inside if() statement. The execution of if() block will depend on whether the condition is true or false.
Define an else Block
- Then we will define an else block to execute a statement in case the condition returns false.
note: The else block isn't mandatory, and it is defined only when we want to address the failure of the condition.
Flowchart of the if else Statement
Following is a flowchart representing if else in javascript:
In the above diagram, we can see that the condition block has two execution paths, one executes when then if the condition is true and executes the if code and the other when if the condition is false and executes the else code. Then it terminates the process.
Note: It can only follow one path at a time.
Example
Let's take an example of a simple if else state to check if you're eligible for voting or not:
In the first function call, the age is 11, and 11 < 18. Thus the condition is true. Since if else in Javascript runs if block, when the condition is true, so program proceeds to run the , if code and then terminates.
In the second function call, the age is 34, and 34 > 11, this the condition age<18 is false, Since if else in Javascript skips if block when the condition is false, thus the program proceeds to else code and then terminates.
The if Statement in JavaScript
As mentioned earlier, in programming, we encounter situations where we have to proceed only if a particular condition is satisfied; in such cases, we can use if statement.
The if statement in javascript executes the statements inside it only if the condition that is mentioned is true.
Note: if statement can be executed independently, i.e. without any else statement.
Syntax:
The if statement is declared by the if keyword followed by a condition enclosed in a bracket followed by the statement to be executed wrapped in curly braces.
Example 1:
In the first output, the condition flag1 is true, thus it executes the if statement and logs the desired output. In the second example, the condition flag2 is false, thus, it doesn't execute the if statement, and due to the absence of the else statement, it outputs nothing.
In the first output, the condition a == b is false as 10 and 100 aren't equal. Thus it doesn't execute the if statement, and due to the absence of the else statement, it outputs nothing. In the second output, the condition a==c is true as 1- is equal to 10; thus it executes the if statement and logs the desired output.
Note: if-else in Javascript runs if block when the condition is true. Otherwise, it proceeds to other conditions.
Example 2:
In the above example, the first input is 11, thus, it returns true for age<18 and false for age>=18. Thus the output is Sorry! You are not eligible for voting.
In the above example, the second input is 34, thus, it returns false for age<18 and true for age>=18. Thus the output is You are eligible for voting.
The if...else Statement in JavaScript
We have already discussed how the if statement executes only when the condition is true. But what if the if statement fails? In such cases, we can use the else statement.
else statement in javascript is used to execute a block when all if conditions fail. In order to write an else block, it is mandatory to declare an if statement, although the vice versa is not true.
Note: In if else in Javascript, the else statement can not be executed independently, i.e. it is mandatory to write an if statement before an else statement.
Syntax:
The if-else statement is declared by declaring if statement followed by else keyword followed by the code to be executed wrapped in curly braces.
In if else in Javascript, the else statement does not need any condition and executes only when if condition fails.
Example:
Explanation of the above examples:
Example 1: In the first example, the condition flag1 is true; thus it executes the if statement and logs the desired output. In the second example, the condition flag2 is false; thus, it skips the code inside the if statement and executes the code inside the else statement and logs the desired output.
Example 2: In the first example, the condition a == b is false as 10 and 100 aren't equal, thus it skips the code inside if statement and executes the code inside the else statement, and logs the desired output. In the second example, the condition a==c is true as 1- is equal to 10; thus it executes the if statement and logs the desired output.
Note: if-else in Javascript runs if block when the condition is true, otherwise it proceeds to other conditions.
Example 2:
In the above example, the first input is 11, thus the condition age<18 returns true, so the if block will be executed.
In the above example, the second input is 34, thus the condition age<18 returns false, so the if block fails thus the else block will be executed.
nested if else Statement in JavaScript
Sometimes we encounter conditions where a specific operation can be processed only when multiple conditions are satisfied.
For e.g., while logging into our social media account the website first checks if our username is in the database, once the condition is satisfied, it takes our password and matches it with the one in their database. Although if the username is not found, the website won't bother to check the password. In such cases, the nested if-else statement can be used to validate multiple layers.
Syntax:
Nested if else statement can be declared by simply declaring an if else statement inside an if statement of an else statement.
Similar to normal if-else statement, in nested if-else, the else block isn't mandatory and can be omitted.
Example
In the above example, the first input is 12 thus it fails the first if condition and heads towards the else statement, then it fails the condition of the second if statement as well; thus it outputs the second else statement code.
The second input is 51 thus it passes the first if the condition so it proceeds to the if statement. Now it fails the second if condition thus it outputs the else statement code.
The third input is 12; thus it fails the first if condition and heads towards the else statement, then it returns true for the condition of the second if statement; thus it outputs the second if statement code.
The second input is 113 thus it passes the first if the condition, so it proceeds to the if statement, it passes the second if condition as well thus it outputs the if statement code.
Note: if-else in Javascript runs if block when the condition is true, otherwise it proceeds to other conditions.
The if...else if... Statement in JavaScript
We often encounter situations where the statement that is processed depends upon the value of the conditional expression. For example, imagine we are writing a program to display the month's name according to the month number (For example: if we enter 1 the program should display 'January', if we enter 4, the program should display April, and so on. In such cases, we need to compare our input with multiple conditions and display the output associated with the condition that returns true.
In such cases, the if else if condition is used. It is used where there are multiple conditions to be checked in order to proceed.
Note: if else if condition should not be confused with nested if-else, in if else if condition, there are multiple conditions, but only one can be executed, but in nested if-else condition, there are multiple conditions, and for the execution of nested condition it is mandatory that the previous condition has returned true (also, in this case, multiple conditions can be true).
Syntax:
In if else in Javascript, the if statement of if-else is declared by declaring the if statement followed by declaring another if statement after the else keyword.
We can add any number of else if statements.
An else statement can also be added in the end of the if, and else if conditions as well. This else will only execute when all if conditions will fail.
note: The else condition should be appended in the end only.
Example:
In the first function call, the input value is 1, now, the first condition gets compared with 1. Since 1==1, thus the expression returns true, thus it outputs January. Now that one condition is found true, the input will not be compared with other conditions, and the program will terminate.
In the second function call, the input value is 3, now the first condition is compared with input, and it returns false (as 3 is not equal to 1), then it is compared with the second condition, and it again returns false. Then it is compared with the third condition and it returns true (since 3 == 3). Thus the program outputs March and terminates.
In the third function call, the input value is 34, now the functions start evaluating the input with respect to all the conditions, and it returns false; thus it processes the else condition.
Note: if-else in Javascript runs if block when the condition is true, otherwise, it proceeds to other conditions.
if else in JavaScript Shortcut: Conditional Operator
So far, we've seen applications of if else statement in multiple manners. However, there is a short and simpler way to implement these if else statements. It is known as the conditional operator.
The conditional operator, is a short-hand form for the implementation of the if else statement. It takes three operands, a condition, followed by a question mark(?), then it takes an expression which is executed when the condition is true, followed by a colon (:), then it takes an expression which is executed when the condition is false.
It is also known as ternary operator, as it operates with three operands, a condition, a truthy statement (that executes only when the condition is true) and a falsy statement (that executes only when the condition is false).
It is mandatory to write an expression for the falsy condition in the ternary operator.
Syntax of the Conditional Operator
It is defined by declaring condition followed by a ? operator, which is followed by a statement which will execute if the condition is true (ifConditionIsTrue), which is followed by a :, which is followed by a statement which will execute if the condition is false (ifConditionIsFalse).
Note: In the conditional operator, it is mandatory to provide all three operands.
Example:
In the first example, the age entered is 16, thus the condition x<16 returns true thus it returns the first statement (which gets returned when the condition is true).
In the second example, the age entered is 21; thus the condition x<16 returns false, thus it returns the second statement (which gets returned when the condition is false).
Note: The condition returns false even for null, NaN, 0, undefined, or empty string.*
Example:
In the above example, all the outputs are falsy values as the input is null, NaN, undefined, empty string and 0, respectively.
Chaining Conditional Operators
We often encounter situations where the statement that is processed depends upon the value of the conditional expression. For example, imagine we are writing a program to display the month's name according to the month number (For example: if we enter 1 the program should display 'January', if we enter 4, the program should display April, and so on. In such cases, we need to compare our input with multiple conditions and display the output associated with the condition that returns true.
We can chain multiple conditions in the conditional operator in order to get the desired output. This can be done by defining multiple conditions and their execution statements using : and ? operators.
Example:
The first output is June, as the value of monthVal is 6, thus it returns the monthVal == 6 condition true.
The second output is March, as the value of monthVal is 3, thus it returns the monthVal == 3 condition true.
The third output is Enter valid input, as the monthVal is 22, which returns false for all the conditions, thus returns the default condition.
Browser Compatibility
if else statement | Conditional operator | |
---|---|---|
Chrome | 1 | 1 |
Edge | 12 | 12 |
Firefox | 1 | 1 |
Internet Explorer | 3 | 3 |
Opera | 3 | 3 |
Safari | 1 | 1 |
The mentioned values are the minimum version of the browser required to support the given statements.
Conclusion
- The if else statement can be used in situations where we have to make decisions depending on the existence of a particular condition.
- The condition should return a true or false value.
- The if statement executes only if the condition is true.
- The else statement is not mandatory and will execute only if the if condition fails.
- The if else statement can be nested or chained using multiple conditions.
- We can also use a conditional operator to write an if else statement in a short form.
- Conditional operators are also known as the ternary operator as they work on three operands.
- In conditional operators, it is mandatory to address the else condition.