WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript If...Else Statements


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


Conditions

When writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.

In JavaScript, we can use the following conditional statements:

  • if statement -Use this statement to execute code only if the specified condition is true
  • if ... else statement -execute code when the condition is true, execute other code when the condition is false
  • if ... else if .... else statement -Use this statement to select one of multiple code blocks to execute
  • switch statement -Use this statement to select one of multiple code blocks to execute

The if Statement

The statement executes code only if the specified condition is true.

Syntax

if (condition)
{
     Code executed when the condition is true
}

Example

Use lowercase if. Using uppercase letters (IF) generates JavaScript errors!

if (time < 18) {
    x = "Good day";
}

The result of x is:

Good day
Try it yourself »
Note that there is no ..else .. in this syntax. You have told the browser to execute code only if the specified condition is true.

The else Statement

Use if .... else statements to execute code when the condition is true and execute other code when the condition is false.

if (condition) { Code executed when the condition is true } else { Code executed when the condition is not true }

Example

When the time is less than 20:00, a greeting "Good day" is generated, otherwise a greeting "Good evening" is generated.

if (time < 18) {
    x = "Good day";
} else {
    x = "Good evening";
}

The result of x is::

Good day
Try it yourself »
Note that there is no ..else .. in this syntax. You have told the browser to execute code only if the specified condition is true.

The else if Statement

Use if .... else if ... else statements to select one of multiple code blocks to execute.

Syntax

if (condition1) {
Code executed when condition 1 is true } else if (condition2) {
Code executed when condition 2 is true
} else {
    Code executed when neither condition 1 nor condition 2 is true
}

Example

If the time is less than 10:00, a greeting "Good morning" is generated, if the time is greater than 10:00 and less than 20:00, a greeting "Good day" is generated, otherwise a greeting "Good evening" is generated:

<script> var d = new Date (); var time = d.gettimes (); if (time <10) { document.write (" Good morning "); } else if (time> = 10 && time <16) { document.write (" Good today "); } else { document.write (" Good evening! "); } </script> Good evening!

The result of x is:

good evening!
Try it yourself »