Skip to main content

How to Use else if in JavaScript with Examples

 

How to Use else if in JavaScript with Examples




The if and else-if statements are commonly used commands in the field of programming. Computer programmers learn if statements during their beginner-level courses, which makes this a very basic lesson for developers. The statement has a very similar use in JavaScript, Java and C, but we will be focusing on how to use if and else if in Javascript, in this article. 

 

“If” is just the first conditional statement, which is followed by a series of conditions that help you make more complex decisions throughout the program. Once you have a stronghold over these conditional statements, you can start working your way through small programs. 

Apart from “If” we have “else-if”, then we have “else-if else-if”, and then there’s nested-if as well. Below you can find each of these if statements explained with examples. 


Using IF in JavaScript

The if statement is always followed by a condition. Then it is further followed by a block of code which is executed if the condition is true. 

Let’s assume we declared a variable x and set its value at 15.

var x = 15; if (x>10) {
document.write("x is greater than 10");
}

Since the if-condition is true because x is greater than 10, a string that says “x is greater than 10” will be printed as a result. 

Using IF Else in JavaScript

The else statement is used when the developer wants to tell their system what to do, in case the If condition is false. 

Let’s assume the value of the variable x is still 15.

var x = 15;

if (x>20) {
	document.write("x is greater than 20");
}
else{
	document.write("x is smaller than 20");
}

As we can see that the if-condition is false in this case, the written code will go on to run the code under the else statement. As a result of this code “x is smaller than 20” will be printed on the screen.

Using Else If in JavaScript

One condition is not always enough for a coder to achieve their goal. In such cases, they need a statement that can cater to more conditions. 

Let’s assume the value of the variable x is 15.

var x = 5;

if (x>20) {
	document.write("x is greater than 20");
}
else if (x>10) {
	document.write("x is greater than 10");
}
elsedocument.write("x is greater than 0");
}

In the above code sample the variable x is put through 3 conditions. Since x is smaller than 20, the first condition is false, but since it is greater than 10, the second condition is true. Hence the code is executed after the second condition and it prints “x is greater than 10”.

Using Nested IF in JavaScript

A nested If-statement is used when you have multiple conditions within a condition. After the first given condition is true, you need another condition to be true, before you can execute the code. 

Let’s assume the value of the variable x is 26.

var x = 26;

if (x>20) {
  if (x%2 == 0)  {
    document.write("x is even and greater than 20");
  } 
}

Here we can see that there’s an if statement inside the first if statement’s loop. In this case, the value of x is tested for the two conditions and the result is printed as “x is even and greater than 20”.

Logical Operators

Apart from the examples seen above, we often use Logical operators to reach our intended goals. Logical operators are used to combine two or more If-statements. The three Logical operators that we will talk about are AND, OR, and NOT. 

AND

When an AND operator is applied to If statements, the following code is only executed if both the conditions are true. In Javascript, AND is denoted by the symbol “&&”

Let’s assume the value of the variable x is 30

var x = 30;

if (x>20 && x%2 == 0) {
	document.write("x is even and greater than 20");
}

Here we can see that there are two conditions inside the If statement connected using AND. When the program runs it goes through the conditions starting from left to right. The AND operator results true when both the mentioned conditions are true. In this case both the conditions are met and a string saying “x is even and greater than 20 is printed”. 

OR

The OR operator is applied the same way as AND. In this case, only one of the two conditions needs to be true for the code to be executed. In Javascript, OR is denoted by the symbol “||”

Here we have the variable x set at the value of 9.

var x = 9

if (x<10 || x>20){
	document.write("x does not lie in the range of 10-20");
}

When the code runs, the program needs only one of the two conditions to be true because of the OR operator, before it runs the following code. In this case, the first condition is true, therefore the result will print, “x does not lie in the range of 10-20”.

NOT

The NOT operator is a negation operator that is represented by the symbol “!” in Javascript. Below is an example of NOT being used in a short program. 

Let’s assume the variable x here denotes a candidate’s age and its value is set at 15.

var x = 15

if (!(x>=18)) {
	document.write("The candidate is not eligible for participation");
}

As this code runs, the program will check the value of x, and if it is not greater than or equal to 18, it will return a string that says “The candidate is not eligible for participation”. 

These are some of the most common uses of the IF statement. If-statements are combined with these common operators quite often by programmers in order to make their program successful. In some cases, the IF statement is replaced with other statements, where found interchangeable, and more befitting. 

Switch statement

The switch statement is often an alternate solution for the use of if-statement. In the case of a switch, there is one expression that is checked once and then compared with a number of cases to see which one is true. You must add 'break' statement at the end of each so only the first matching case will be executed.

The variable status denotes the remarks of a student in an exam.

var status
var marks = 85

switch(true) {
case (marks >= 50):
    status = "pass";
    break
case (marks < 50):
    status = "fail";
    break
default:
    status = "please enter marks";
    break
}

document.write(status)

In this code, the expression first tests the value of marks against a different set of cases. If a case is true, it prints “pass'' and the ‘break’ statement then breaks the code. However, if the first case is not true, it moves down to the second case and if that is true, it prints “fail”, and so on. In case of a name not matching ‘case’, it will execute the ‘default’.

Final Thoughts on How to Use else if in JavaScript

We hope that this article cleared all your confusion related to using the else if statement in JavaScript and these other statements. 

Do you still have any questions? Let us know in the comments below, we’ll be happy to help.



Comments

Popular posts from this blog

Organizing Data In Table: A Quick Guide

  Organizing Data In Table: A Quick Guide We can use tables to structure data in columns and rows. The table is the HTML way to lay out the data. The CSS way to create the layout on the web page is  CSS float ,  flexbox , and  CSS grid . We cover an example to understand how to create a table on the web page. You can view the HTML table example at the below codepen link: https://codepen.io/taimoorsattar/pen/NWpdwbp For example, we can create a table in HTML for customer’s grocery item bill as below: < table border = "3" cellpadding = "10" cellspacing = "0" > < caption > Grocery Items Bill </ caption > < thead > < colgroup > < col width = "60%" > < col width = "20%" > < col width = "20%" span = "1" style = "background-color:#f1f1f1;" > </ colgroup > < tr > < th align = ...

5 CSS Tips and Tricks to Try in Your Next Project

  5 CSS Tips and Tricks to Try in Your Next Project Looking for inspiration on how to add a twist to your project design? Take a look at these 5 CSS techniques and have fun experimenting with some bold ideas! 1. Bring back the 90’s with the background-clip Have you ever wondered how to apply a gradient or a texture to the text in CSS? The good news is you can easily achieve that with the background-clip property! First, we need to apply the background color to our  <h1> , then use the value text for the  background-clip  property and set the text color to transparent. < h1 class = "wordart" > The background is clipped to this text </ h1 > h1 { background-color: #ff1493; background-image: linear-gradient(319deg, #ff1493 0%, #0000ff 37%, #ff8c00 100%); } .wordart { -webkit-background-clip: text; color: transparent; } And voilĂ , the 90’ style WordArt is ready! 2. Crazy shapes with clip-path If you like to experiment with your ...

1.Change windows password without knowing the existing password

We all know that to change password in windows we need to enter the existing password and then we can proceed to enter the new password.However there is a trick to change password without knowing the existing password. This trick comes handy when the system is logged in and we have forgotten the password or to pull a prank on your friend(do it at your own risk) Step 1: Right click on computer and select manage Step 2: click on Local users and Groups and click on users. On the right pane you will see list of users. step 3: Right click on any user whose password you want to change and click on set password: step 4: click on proceed(Don’t worry about the message) step 5: Enter the new password step 6: Click on ok and your password will change. You can even use the same method to change HOMEGROUP password. (NOTE: This trick works on WIN 7, 8 , 8.1 ,10)