totn JavaScript

JavaScript: if-else Statement

This JavaScript tutorial explains how to use the if-else statement with syntax and examples.

Description

In JavaScript, the if-else statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.

Syntax

There are different syntaxes for the if-else statement.

Syntax (if)

The syntax for the if statement in JavaScript is:

if (condition) {
   // statements to execute when condition is TRUE
}

You use the if syntax, when you want to execute statements only when the condition is TRUE. Although it is best practice to use { }, you can omit them if there is only one statement to execute as in the following syntax:

if (condition)
   // only one statement to execute when condition is TRUE

Syntax (if-else)

The syntax for the if statement followed by an else in JavaScript is:

if (condition) {
   // statements to execute when condition is TRUE

} else {
   // statements to execute when condition is FALSE

}

You use this syntax, when you want to execute one set of statements when the condition is TRUE or a different set of statements when the condition is FALSE.

Syntax (else if)

The syntax for the else if statement in JavaScript is:

if (condition1) {
   // statements to execute when condition1 is TRUE

} else if (condition2) {
   // statements to execute when condition1 is FALSE and condition2 is TRUE

} else {
   // statements to execute when both condition1 and condition2 are FALSE

}

The else if is created by nesting multiple if statements. You use this syntax, when you want to execute one set of statements when condition1 is TRUE, a different set of statements when condition1 is FALSE and condition2 is TRUE, or a different set of statements when all previous conditions (ie: condition1 and condition2) are FALSE.

Note

  • Once a condition is found to be TRUE, the if-else statement will execute the corresponding code and not evaluate the conditions any further.
  • If no condition is met, the else portion of the statement will be executed.
  • It is important to note that the else if and else portions are optional.

Example

The following is example using the if-else statement in JavaScript:

// Set the TechOnTheNet technology to JavaScript
var totn_technology = 'JavaScript';

if (totn_techonology == 'SQL' ) {
    console.log('TechOnTheNet SQL');
    
} else if (totn_technology == 'JavaScript') {
    console.log('TechOnTheNet JavaScript');

} else {
    console.log('Other TechOnTheNet technologies');
}

In this if-else statement example, the code will execute different statements depending on the value of the totn_technology variable. Since the totn_technology variable has been set to the string 'JavaScript', the statements within the else if section of the code will be executed.

In this example, the following will be output to the web browser console log:

TechOnTheNet JavaScript