JavaScript if else Statement

JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement. There are three forms of if statement in JavaScript.They are:

  • if Statement
  • if else Statement
  • if else if Statement


Javascript if Statement

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax:

if (expression) {
// Statements to be executed if expression is true
}

Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.

Example:

if (age>18) {
document.write ("An adult person.");
}

Run Example


Javascript if...else Statement

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

Syntax:

if (expression) {
// Statements to be executed if expression is true
} else {
// Statement 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, are executed. If the expression is false, then the given statement(s) in the else block are executed.

Example:

if (age>18) {
document.write ("An adult person.");
} else {
document.write ("Not an adult person.");
}

Run Example


Javascript if...else if... Statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

Syntax:

if (expression 1) {
// Statements to be executed if expression 1 is true
} else if (expression 2) {
// Statements to be executed if expression 2 is true
} else if (expression 3) {
// Statements to be executed if expression 3 is true
} else {
// Statement to be executed if no expression is true
}

There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.

Example:

if (name == "smith") {
document.write ("play cricket");
} else if (name == "ronaldo") {
document.write ("play football");
} else if (name == "sania") {
document.write ("play tennis");
} else {
document.write ("unknown");
}

Run Example