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

Detecting The User's Color Scheme Preference With CSS

Detecting The User's Color Scheme Preference With CSS If you’re a developer, chances are that you use dark mode on your machine and code editor. If not, what are you waiting for? Join the dark side! Jokes apart, it is common nowadays to allow users to select a different theme when visiting a website. Now you can do this with CSS only, not the theme selection itself, for that you still need JS but with CSS you can now detect the user’s machine color scheme (light or dark) and display the correct colors on your website immediately. To do this we need to use the CSS variables. According to the website  Can I use , the “CSS variables” feature is available on 95% of the currently used browsers around the world. We also need to use the  prefers-color-scheme  media query, which according to  Can I use  is supported by about 90% of the currently used browsers. In this article, I will show you how to use the CSS variables and the  prefers-color-scheme  to setup the default colors of the web

Top 10 Python Frameworks Ranked on Github

  Top 10 Python Frameworks Ranked on Github A framework is a library that makes building web applications easier. Frameworks provide a structure for developers so they can focus more on the business logic of their applications. Python has one of the largest ecosystems with a great number of different libraries, frameworks, and tools for developers. Let's take a look at the best Python  frameworks for web development . Here is a list of the ten highest-ranked Python frameworks  on GitHub. Django    Django is an open-source framework that makes things very fast and scalable. It enables programmers to develop apps and websites of different complexity within a short time. Django's advantages are reusability of components, less code, low coupling, and a principle of not repeating. Moreover, the framework is easy to use. You don't need special tools to develop a Django project. You can write it in a typical text editor, such as notepad. In this way, Django is easy to learn for be

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)