Conditional statements are used to perform different actions based on different conditions.

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The switch statement is described in the next chapter.

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

<span style="color: mediumblue;">if</span> (_condition_) {

  <span style="color: green;">//</span>_ block of code to be executed if the condition is true_

}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

Example

Make a “Good day” greeting if the hour is less than 18:00:

<span style="color: mediumblue;">if</span> (hour < <span style="color: red;">18</span>) {

 greeting = <span style="color: brown;">"Good day"</span>;

}

The else Statement

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

<span style="color: mediumblue;">if</span> (_condition_) {

  <span style="color: green;">//</span>_ block of code to be executed if the condition is true_

} <span style="color: mediumblue;">else</span> {

  <span style="color: green;">//</span>_ block of code to be executed if the condition is false_

}

Example

If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":

<span style="color: mediumblue;">if</span> (hour < <span style="color: red;">18</span>) {

  greeting = <span style="color: brown;">"Good day"</span>;

} <span style="color: mediumblue;">else</span> {

 greeting = <span style="color: brown;">"Good evening"</span>;

}

#javascript #if else #html5 #css #js

JavaScript if else if else and Switch Budget Calculator Project
16.95 GEEK