JavaScript if else Statement

You are Here:

JavaScript if else Statement

The if statement will be executed if a specified condition is true. Otherwise, the else statement will be executed.

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 if and else block.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Try to change "num = 150" to "num = 50"</p> <p id="point"></p> <p id="point1"></p> <script> var x = document.getElementById("point"); var y = document.getElementById("point1"); var num = 150; if(num < 100) x.innerText = "num is less than 100"; else x.innerText = "num is greater than 100"; y.innerText = "I will always execute"; </script> </body> </html>

Syntax

if(condition) // one line code else // one line 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 if and else block.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Try to change "num = 150" to "num = 50"</p> <p id="point"></p> <p id="point1"></p> <script> var x = document.getElementById("point"); var num = 150; var txt = ""; if(num < 100){ txt = "num is less than 100"; x.innerText = txt; } else{ txt = "num is greater than 100"; x.innerText = txt; } y.innerText = "I will always execute"; </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