WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript If...Else Statements


Conditional articulations are utilized to perform distinctive activities dependent on various conditions.


Conditional Statements

Very frequently when you compose code, you need to perform diverse activities for various decisions.

You can utilize restrictive explanations in your code to do this.

In JavaScript we have the accompanying contingent statements:

  • Use if to determine a square of code to be executed, if a predefined condition is true
  • Use else to determine a square of code to be executed, if a similar condition is false
  • Use else if to indicate another condition to test, if the principal condition is false
  • Use switch to determine numerous elective squares of code to be executed

The if Statement

Use the if articulation to determine a square of JavaScript code to be executed if a condition is true.

Syntax

in the event that (condition) {
    square of code to be executed if the condition is true
}

Example

Make a "Good day" welcoming if the hour is not exactly 18:00:

on the off chance that (hour < 18) {
    welcoming = "Good day";
}

The consequence of welcome will be:

Try it yourself »

The else Statement

Use the else proclamation to determine a square of code to be executed if the condition is false.

on the off chance that (condition) {
    square of code to be executed if the condition is true
} else {
    square of code to be executed if the condition is false
}

Example

If the hour is under 18, make a "Good day" welcoming, generally "Good evening":

on the off chance that (hour < 18) {
    greeting = "Good day";
} else {
    welcoming = "Good evening";
}

The aftereffect of welcome will be:

Try it yourself »

The else if Statement

Use the else if proclamation to determine another condition if the primary condition is false.

Syntax

in the event that (condition1) {
    square of code to be executed if condition1 is true
} else if (condition2) {
    square of code to be executed if the condition1 is false and condition2 is true
} else {
    square of code to be executed if the condition1 is false what's more, condition2 is false
}

Example

If time is under 10:00, make a "Good morning" welcoming, if not, yet time is under 20:00, make a "Good day" welcoming, generally a "Good evening":

in the event that (time < 10) {
    welcoming = "Good morning";
} else if (time < 20) {
    welcoming = "Good day";
} else {
    welcoming = "Good evening";
}

The consequence of welcome will be:

Try it yourself »