JavaScript if Statement

The if statement in JavaScript, is used to execute some block of code only if the given condition evaluates to be true. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      let x = 5;
      if(x%2 == 0)
         document.getElementById("xyz").innerHTML = "Even number";
   </script>
   
</body>
</html>
Output

In above example, the following statement:

document.getElementById("xyz").innerHTML = "Even number";

will be executed, only if the following condition:

x%2 == 0

evaluates to be true. Since the condition x%2 == 0 or 5%2 == 0 or 1 == 0 evaluates to be false, therefore nothing will produce on the output.

JavaScript if Statement Syntax

The syntax of if statement in JavaScript, is:

if(condition) {
   // block of code to execute, if condition evaluates to be true 
}

JavaScript if Statement Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      let a = 10, b = 20;
      if(b>a)
         document.getElementById("abc").innerHTML = "The value of 'b' is greater than 'a'";
   </script>
   
</body>
</html>
Output

Nested if Statement in JavaScript

The if inside another if considered as nested if statement. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="myPara"></p>
   
   <script>
      let m = 10;
      if(m>0)
      {
         if(m==10)
         {
            document.getElementById("myPara").innerHTML = "The value is 10";
         }
      }
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »