JavaScript If Statement

In real-time programming, the JavaScript If Statement is one of the most valuable decision-making statements. JavaScript If Statement allows the compiler to test the condition first, depending upon the result, it will execute the statements. If the test condition is true, then only statements within the if statement executed.

JavaScript If Statement Syntax

The JavaScript If Statement has a simple structure:

if (test condition)
{
 
  Statement 1;
  Statement 2;
  ………….
  ………….
  Statement n;
}

From the above JS code, If the test condition in the If statement is true, the statements (Statement 1, Statement 2, Statement 3, ……., Statement n) will execute. Otherwise, all these statements will skip.

JavaScript If Statement Example

This program will check for the positive number using JavaScript if statement

<!DOCTYPE html>

<html>
<head>
    <title> JavaScript If Statement </title>
</head>
 <h1> JavaScript If Statement </h1>
<body>
<script>
  var number = prompt("Please Enter any integer Value:", "9");
  if( number >= 1 )
  {
    document.write("You Have Entered Positive Integer");
  }
</script>
</body>
</html>

For the single statement, curly brackets are not required in JavaScript, but for multiple or group of statements, it is mandatory. It is always good practice to use curly brackets following the JavaScript If statements.

When you open the browser, the prompt box will be opened with default value. We left to default 9 and Clicked OK.

JavaScript If Statement

You Have Entered Positive Integer: 9

If you look at the above if condition, Value stored in the number variable is greater than zero. That’s why it is displaying statement inside the curly brackets ({ }).

From the above example, what happens if the condition fails? (number < 1). 

It prints nothing because we don’t have anything to print after the if statement. I hope you are confused. Let us see the flow chart of If Statement for better understanding.

Js If Statement Example 2

<!DOCTYPE html>

<html>
<head>
    <title> JavaScript If Statement </title>
</head>
 <h1> JavaScript If Statement </h1>
<body>
<script>
  var number = prompt("Please Enter any integer Value:", "9");
  if( number >= 1 )
  {
    document.write("You Have Entered Positive Integer:  " + number);
  }
  document.write("<br \> This Message is not coming from IF STATEMENT\n");
</script>
</body>
</html>

Here also we left the number to default 9

JavaScript If Statement 3

If you can observe from the above output, it is displaying both the statements because 9 is greater than 1. Let’s try the negative values in the prompt box to fail the condition deliberately.

-33

If condition failed because -33 is less than 1, and it displays nothing from the JS If statement block. So, it is showing only one statement outside the statement block.

JavaScript If Statement

This Message is not coming from IF STATEMENT