The JavaScript If Else Statement is an extension of the If statement. We already saw the Js If Statement, it only executes the statements when the given condition is true. If the condition is false, it will not run any statements.
In the real world, it would be nice to execute something when the condition fails. To do so, We have to use this JavaScript If else statement. Here, Else statement will execute the statements when the condition fails. The syntax of the If Else Statement in JavaScript is as follows:
if (Test condition) { //If the condition is TRUE then these statements will be executed True statements; } else { //If the condition is FALSE then these statements will be executed False statements; }
If the test condition in the above structure is true, the True statements will execute. If it is false, the False statements executed.
Flow Chart for JavaScript If Else Statement
Let us see the flow chart of the JavaScript if else statement for better understanding.
If the JavaScript If Else Statement test condition is true, STATEMENT 1 is executed, followed by STATEMENT N. If it is False, STATEMENT 2 will execute, and then STATEMENT N executes. Because it is out of the if else condition block, and it has nothing to do with the condition result.
JavaScript If Else Statement Example
In this if else statement example program, we are going to place four different statements. If the condition is true, we will display two different statements. If the condition is false, JavaScript will display another two statements. Please refer to JS If Statement article.
<!DOCTYPE html> <html> <head> <title> JavaScript Else Statement </title> </head> <h1> JavaScript Else Statement </h1> <body> <script> var marks = 60; if( marks >= 50 ) { document.write("<b> Congratulations </b>"); //s1 document.write("<br\> You Passed the subject" ); //s2 } else { document.write("<b> You Failed </b>"); //s3 document.write("<br\> Better Luck Next Time" ); //s4 } </script> </body> </html>
OUTPUT 1: Here marks is 60 and the Condition is TRUE that’s why, statements inside the If Statement is displayed as Browser output
OUTPUT 2: Here, we changed the marks variable to 30. It means the Condition is FALSE that’s why statements inside the Else Statement displayed as an output