JavaScript If Else Statement

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.

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

JavaScript Else Statement 1

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

JavaScript Else Statement

You Failed
Better Luck Next Time