JavaScript If Else Statement

The JavaScript If Else Statement is an extension of the If which we already explained before. And it only executes the code when the given expression evaluated to true. If the condition is false, it will not run any code inside the block.

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 will execute the statements when the condition fails. The syntax of the JavaScript If Else Statement is as follows:

if (Test condition)
  //If the condition is TRUE then these will be executed
  True statements;

  //If the condition is FALSE then these 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 code will execute.

JavaScript If Else Statement Example

In this JavaScript if else statement example program, we are going to place four different statements. If the condition is true, we will display two different lines. If the condition is false, JavaScript will display another two. Please refer to JS If condition article.

<!DOCTYPE html>

    <title> JavaScriptElseStatement </title>
 <h1> JavaScriptElseStatement </h1>
  var marks = 60;
  if( marks >= 50 )
    document.write("<b> Congratulations </b>"); //s1
    document.write("<br\> You Passed the subject" ); //s2
    document.write("<b> You Failed </b>"); //s3
    document.write("<br\> Better Luck Next Time" ); //s4

OUTPUT 1: Here marks is 60 and the Condition is TRUE that’s why, statements inside the If Statement is displayed as Browser output

JavaScript If Else Statement 1

OUTPUT 2: Here, we changed the marks variable to 30. It means the Condition is FALSE that’s why code inside the Else block displayed as an output


You Failed
Better Luck Next Time