How to Use if…else Statements in JavaScript

  • 6 min read
  • December 2, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

An if statement is a conditional statement, as the name implies.

Conditional statements are used very often in code. Conditional statements are used to execute specified actions only if a provided condition (or set of conditions) is met.

JavaScript has three types of conditional statements:

  1. if statements (including else if and else)
  2. switch statements
  3. ternary operators

This article will explore the if statement in detail.

Basic if statement example

Below is a basic example of an if statement:

let x = 7;
let y = 5;
if (x > y) console.log('x is greater than y');
// Expected output: x is greater than y

The above example defines two variables – x and y. x is given the value of 7, and y is given the value of 5. The example then makes a choice based on comparing the two values with the greater than  operator (>). In simple words, the action taken is as follows: if x is greater than y, print “x is greater than y” to the console.

All if statements follow the same general logic: if an expression is true (a condition is met) then execute the provided code.

Note: the example above uses the short syntax. The full syntax is covered below under Syntax.

Note: In most cases, if statements require the use of comparison operators, or logical operators, or both.

Note: The expression of the condition has to be something that can be evaluated to either true or false.

In the above example code, if the expression (x > y) is false nothing happens. If you wish to execute a code in the event that a condition is not met, use else.

Basic if…else statement example

The example below demonstrates how to augment an if statement with an else clause:

let x = 7;
let y = 5;
if (x > y) console.log('x is greater than y')
else console.log('x is not greater than y');

In the example above, an else statement was added. With this change, if the expression for the condition (x > y) is evaluated to be false, “x is not greater than y” will be printed to the console.

Note: Just because the expression evaluated to false, that does not mean that x is greater than y. This is an invalid assumption for two reasons:

  1. The variables can contain any data type, and are not restricted to only numeric values – the returned false value can occur simply because the two operands cannot be compared against each other using the greater-than operator.
  2. The two values might instead be equal.

We can use else if to cover these types of multiple conditions.

Basic else if statement example

Below is an example of an if statement that covers multiple potential cases using else if:

let x = 7;
let y = 't';
if (x > y) console.log('x is greater than y')
else if (y > x) console.log('y is greater than x')
else if (x == y) console.log('x is equal to y')
else console.log('check your variables');
// Expected output: check your variables

The code above covers the three potential results from comparing two numbers: the first number is greater than the second; the second number is greater than the first; or the two numbers are equal. If all three return false, this may indicate that there is a problem with the data being processed. In the example above, for instance, the String ‘t’ is evaluated against the Number 7. This type of comparison cannot be assessed with the greater than operator, resulting in the final else clause being invoked.

If statement functionality

With if statements, every statement is evaluated to be either true or false. If the expression is evaluated to be true, the provided code block will be executed and the following statements will not be read. Meaning, if x is greater than y the program will not check the remaining statements. Thus, it is important to ensure that your if statements handle very specific cases – in the example above, this is comparing the values of x and y.

Nested if…else statements

It is possible to have if statements nested within other if statements:

let sandwich = true;
let cheese = true;
let salad;
let avocado;
if (sandwich) {
    if (cheese) console.log('Preparing cheese sandwich')
    else console.log('Preparing avocado sandwich')
} else {
    if (cheese) console.log('Preparing cheese salad')
    else console.log('Preparing avocado salad')
}

The code above simulates a restaurant where you can order either a sandwich or a salad. Both the sandwich and the salad can be made with either cheese or avocado.

This example does not contain comparison operators, instead each expression is simply evaluated to be true or false due to the input data being Boolean. Currently the code above will print ‘Preparing cheese sandwich’ to the console because both sandwich and cheese are true.

If the variable sandwich instead evaluates to false, the second else will come into play. This is the else for the first if statement.

If the variable cheese also evaluates to false, the code above will print ‘Preparing avocado salad’ to the console. This happens due to the structure of the conditions above – when sandwich is false, the code jumps to the second else, and when cheese is false, the program will reach the third else and execute its console.log() method.

Syntax

This is the full syntax for if statements:

If (condition1) {

codeBlock1

} else if (condition2) {

codeBlock2

} else {

codeBlock3

}

  • condition: wrapped with parentheses – an expression which evaluates to either true or false.

The curly brackets are not always required, as seen in the code snippets above, but it is considered best practice to use them for if statements. They are required when there is more than one statement to execute in a given codeBlock for a condition.

Once a condition is evaluated to be true, its respective codeBlock is executed and the remaining part of the if statement will not be read by the program.

  • else if: these statements provide alternative conditions to be evaluated. It is possible to provide as many else if statements as you wish.
  • else: serves as a default action – if all prior conditions were evaluated to be false, the codeBlock of the else statement is executed.

 

Related Articles

JavaScript – How to Use switch Statements

JavaScript – How to Use for Statements

JavaScript – Data types Explained

 

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement