JavaScript if else both are conditional statements that are used to do different tasks based on a given condition.
Basically, JavaScript has multiple types of conditional statements which we use according to our task at the time of web development. There is 4 type of conditional statement in JavaScript.

Introduction to JavaScript else if Statement
else if Statement mainly executes the block of code when specified if the condition returns false.
Syntax of JS else if Statement
1 2 3 4 5 6 7 8 9 |
if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true and expression 1 is false } else if (expression 3) { Statement(s) to be executed if expression 3 is true and expression 2 is false } else { Statement(s) to be executed if no expression is true } |
Javascript Conditional Statements
At the time of doing the code, we execute JS conditional statements based on the given conditions.
Here are some of the statements are which we use,
If
is used to specify the condition, if the condition is true then it executes the block of code specified inside the if block.else
is defined with an if condition, which executes the block of code when the if condition result is false.- When we want to use multiple conditions then we use
else if
condition, it executes the code if the if conditions will return false. - At last, there is
switch
which helps to specify multiple blocks to be executed.
Also Read: How to Embed PDF in Website Using HTML
Example of JS else if Statement :
1 2 3 4 5 6 7 8 |
var x = 40; if (x > 50) { /* do something */ } else if (x > 5) { /* do something */ } else { /* do something */ } |
Code Explanation:
- In this example, we create a global variable and assign an integer value to it.
- On the second line, we set the condition inside the if block, where we check whether the integer is greater than the given number is or not.
- If the
if
the condition returns false then it will execute theelse if
condition. - Else condition executes when no conditional statement is true.
Live Example of Else if and If else Statement in JavaScript
See the Pen by Bikash Panda (@phpcodertech) on CodePen.
In the above example, we create a program to check the language string in the if and else if conditions.
Where we first define a variable and set the string value. Then we check the language with == double equal operator to check whether both are equal or not.
If the condition is not satisfied then it goes to the else if condition.
As in our example if the stated condition is false and it goes to the else if block where it returns true and prints the value on the web page.
I hope you understand things, please let me know if you facing any issues.
Also Read: jQuery Signature Pad with saving As Image Using html2canvas
Happy Coding..!
4 Replies to “JavaScript if else Statement: Detailed Article”