JavaScript If Else Statement

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

It would be nice to execute something in the real world 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 If Else Statement is as follows:

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

else
{
  //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 if else example program, we will 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 If condition article.

<!DOCTYPE html>

<html>
<head>
    <title> JavaScriptElseStatement </title>
</head>
 <h1> JavaScriptElseStatement </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 are 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

JavaScriptElseStatement

You Failed
Better Luck Next Time