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

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 ...

Building A Node.js Based CLI For Real-Time COVID-19 Vaccination Tracking

Why Build? As we already know the whole world is suffering from COVID-19 and the vaccinations are going in full swing everywhere. Finding a slot is getting tougher in our country India as we have a huge population to be vaccinated. Numerous times we have to go to CoWin site to search for a slot and slots are always full. It is pretty time-consuming and irritating. Being a developer, I thought most of the time is usually spent by us in the terminal so why can't we have a basic terminal-based app to save time. So this post will help you in two ways     Learn how to create Node.js based CLI's     Get real-time info about vaccination slots for your area. Let's begin our initial setup! Pre-requisite  – We are assuming you have installed Node.js and npm, If not you can install from  here So as a first step lets initialize our project using command npm init Enter the basic details as shown below. This will create package.json file in the folder cowinCLI. The ne...

Passwords Suck: Here Are 4 Ways We Can Fix Them

  Passwords Suck: Here Are 4 Ways We Can Fix Them With so many websites and platforms on which we set complicated passwords, remembering them is becoming  a memory challenge . Naturally, most of us forget passwords from time to time.  In 2004, Gates predicted that passwords would die out. But, in 2021, we are still using them to log into our social platforms and emails, among many other uses. There were also other criticisms regarding the level of security and protection passwords provide. Cybersecurity professionals and businesses criticize individuals for bad password choices, without noting that technologies allow them to set such passwords. However, many people continue to set weak passwords and appear to be oblivious of common best practices. Many businesses provide no upfront instructions on how to pick the passwords they require us to have. Probably, it’s because they believe we already know or can find out this information elsewhere. However, the fact th...