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 code block. If the test condition is true, then only the if statement execute a block of code.

JavaScript If Statement Syntax

The JavaScript If Statement has a simple structure:

if (test condition)
{
 
  Statement1;
  Statement2;
  ………….
  ………….
  StatementN;
}

From the above JS code, when the test condition in the If is true, the Statement1, 2, 3, ……., n will execute. If condition is false, all these lines will skip.

JavaScript If Statement Example

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

<!DOCTYPE html>

<html>
<head>
    <title> Example </title>
</head>
 <h1> JavaScriptIfStatement </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 line, curly brackets are not required in JavaScript, but for multiple or block of code, 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.

Example

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 code 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 condition. I hope you are confused. Let us see the flow chart of If block for better understanding.

JavaScript If Statement Example 2

<!DOCTYPE html>

<html>
<head>
    <title> JavaScriptIfStatement </title>
</head>
 <h1> JavaScriptIfStatement </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 document write lines because 9 is greater than 1. Let’s try the negative values in the prompt box to fail the condition deliberately.

-33

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

JavaScript If Statement

This Message is not coming from IF STATEMENT