HtmlCssMonk

If Statements in JavaScript | Learn basic JavaScript

technology, laptop, keyboard

DESCRIPTION

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. This statement is a part of JavaScript’s “Conditional” Statements, which are used to perform different actions based on different conditions.

Flow of If…else

JavaScript supports the following forms of If…else

  • if statement
  • if…else statement
  • if…else if… statement.

If Statement

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax –

if (expression) { 
        Statement(s) to be executed if expression is true
 }

Example –

<html>

<body>
  <script type="text/javascript">
    var age = 20;

    if (age > 18) {
      document.write("<b>You can Vote.</b>");
    }
  </script>
</body>

</html>

This Code will produce the following result on your webpage –


If…else Statement

The ‘if…else’ statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

Syntax-

if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}

Example –

<html>

<body>
  <script type="text/javascript">
    var age = 15;

    if (age > 18) {
      document.write("<b>You can Vote.</b>");
    } else {
      document.write("<b>You are not eligible to vote.</b>");
    }
  </script>
</body>

</html>

This Code will produce the following result on your webpage –


If..else..if Statement

The if…else if… statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

Syntax –

if (expression 1) {
     Statement(s) to be executed if expression 1 is true
  } else if (expression 2) {
     Statement(s) to be executed if expression 2 is true
  } else if (expression 3) {
     Statement(s) to be executed if expression 3 is true
  } else {
     Statement(s) to be executed if no expression is true
}

Example –

<html>

<body>
  <script type="text/javascript">
    var book = "maths";

    if (name == "history") {
      document.write("<b>History Book</b>");
    } else if (book == "maths") {
      document.write("<b>Maths Book</b>");
    } else if (book == "economics") {
      document.write("<b>Economics Book</b>");
    } else {
      document.write("<b>Unknown Book</b>");
    }
  </script>
</body>
<html>

This Code will produce the following result on your webpage –


Next topic – Switch statement in JS

Previous topic – Operator in JS


Leave a Comment

Your email address will not be published. Required fields are marked *