JavaScript If Statement

In real-time programming, the JavaScript If Statement is one of the most valuable decision-making statements. The 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 controller executes a code block.

JavaScript If Statement Syntax

The If Statement has a simple structure:

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

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

JavaScript If Statement Example

This program will check for a positive number using this.

<!DOCTYPE html>

<html>
<head>
    <title> Example </title>
</head>
 <h1> Js Example </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 blocks of code, it is mandatory. Using curly brackets following the If code is always good practice.

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

Example

You Have Entered Positive Integer: 9

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

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

It prints nothing because we have nothing to print after the if condition. I hope you are confused. Let us see the flow chart of the If block for a better understanding.

If Statement Example 2

<!DOCTYPE html>

<html>
<head>
    <title> Example </title>
</head>
 <h1> Js </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>

In this JavaScript If statement example, 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 the expression fails because -33 is less than 1, it displays nothing from the JavaScript If condition or statement block. So, it is showing only the code outside the block.

Js

This Message is not coming from IF STATEMENT