JavaScript else if Statement

You are Here:

JavaScript else if Statement

The else if statement executes a block if the specified condition is true. This occurs only when the preceeding condition in the if or else if failed.

Note: You can use multiple else if statement one after the other.

Without Using Curly Brackets

Note: It is not necessary to use open and close curly brackets if you want to execute just one statement in the else if block.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var sea = "blue"; var txt = ""; if(sea == "green") txt = "Sea is green in color"; else if(sea == "blue") txt = "Sea is blue in color"; else txt = "Sea is white in color"; x.innerText = txt; </script> </body> </html>

Syntax

if(condition) // Code else if(condition) // Code else // Code

Using Curly Brackets

Note: It is necessary to use open and close curly brackets if you want to execute more than one statement in the else if block.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var sea = "blue"; var txt = ""; if(sea == "green"){ txt = "Sea is green in color"; x.innerText = txt; } else if(sea == "blue"){ txt = "Sea is blue in color"; x.innerText = txt; } else{ txt = "Sea is white in color"; x.innerText = txt; } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author