What is the if...else statement in JavaScript?



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

Syntax

Here’s the syntax −

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

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, is executed. If the expression is false, then the given statement(s) in the else block is executed.

Example

You can try to run the following to learn how to work with the if…else statement in JavaScript

Live Demo

<html>
   <body>
      <script>
         var age = 10;

         if( age > 18 ) {
            document.write("Eligible to vote!");
         } else {
            document.write("<b>Not eligible to vote!");
         }
         //-->
     </script>
   </body>
</html>
Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest


Advertisements