Skip to content

JavaScript if else statement | Basic code

  • by

Using JavaScript if else statement you can make a decision-maker program. The if statement executes a statement if a specified condition is truthy. If the condition is falsy, else block code will execute.

if (condition) {
   statement1
} else {
   statement2
}

The else statement to specify a code block to be executed if the condition is false.

JavaScript if else

Simple example code check if the number is positive or negative/zero. The example shows the control statement that allows JavaScript to execute statements in a more controlled way.

<!DOCTYPE html>
<html>
<body>

  <script>
    const number = prompt("Enter a number: ");

    if (number > 0) {
      console.log("The number is positive");
    }

    else {
      console.log("The number is either a negative number or 0");
    }

    console.log("The if...else statement");
  </script>

</body>
</html> 

Output:

JavaScript if else statement

Multiple if...else statements can be nested to create an else if clause.

if (condition1)
  statement1
else if (condition2)
  statement2
else if (condition3)
  statement3
...
else
  statementN

Do comment if you have any doubts or suggestions on this JS if else topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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