Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript If Statement

Computer application rarely follow a linear path during execution. The application usually has to choose the execution path depending on the state of the given condition. For example, if you try to access the dashboard for a protected application, you will first have to check if the user is logged in. If the answer is yes, then you grant access else you redirect the user to the dashboard. The if statement allows us to accomplish this. The if statement is used to set a condition then setting up the execution path. The condition must either evaluate to true or false.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-ifs

Open the directory javascript-ifs in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • ifs.js - this file will be used to for code dealing with the if statement

The following visualizes our project setup

javascript-ifs
-ifs.js

Open the directory javascript-ifs in Visual Studio Code or your favorite code editor

JavaScript If Statement Syntax

The syntax for the if statement in JavaScript is as follows

if (condition == true){
	//do something
}

HERE,

  • if (condition == true){...} the if statement is used to start the if statement. The condition should be enclosed in parenthesis and it should evaluate to either true or false. The comparison of the condition should be done with double equal signs ==. We can use a boolean value or use an expression. The code block for the if statement should be between {} curly brackets.
  • //do something represents the code that should be executed if the condition evaluates to true.

JavaScript If Statement Example

Now that we have covered the syntax for the if statement, let us look at a practical example. We will create a function that displays the message "Time to party" if the day is Saturday.

Open the file ifs.js that we created during the project setup and then add the following results.

let day = 'Saturday';

if(day == 'Saturday'){
    console.log('Time to party');
}

HERE,

  • let day = 'Saturday'; defines a variable day that is assigned the value Saturday.
  • if(day == 'Saturday'){...} uses the if statement to check if the value of the variable day is equal to Saturday. The code between the curly brackets is executed if the condition is true.

Open the terminal in Visual Studio Code and run the following node command

node ifs.js

You should be able to get the following results

Time to party

Let's now modify the code to the following

let day = 'Monday';

if(day == 'Saturday'){
    console.log('Time to party');
}

HERE,

  • let day = 'Monday'; initializes the variable day to the value Monday
  • if(day == 'Saturday'){...} checks if the value of day is Saturday

Executing the above code prints nothing in the terminal. This is because Monday is not equal to Saturday so our condition is evaluating to false.

But what if you want to do something even if the condition is false? This is where the else statement comes in.

JavaScript Else Statement

The else statement is used to define the code block that should be executed when the condition evaluates to false. We will modify the above example so that the program shows a messages regardless of the state of condition

Modify the code for ifs.js as follows

let day = 'Monday';

if(day == 'Saturday'){
    console.log('Time to party');
}else{
    console.log('Monday blues');
}

HERE,

  • else{...} the keyword else is used to define the code block that should be executed if the condition is false.

Open the terminal and run the following command

node ifs.js

You should be able to get the following results

Monday blues

Else if statements

Sometimes you may need to work with more than one condition. The else if statement is used to accomplish that. We will now look at a simple example that uses the else if statement.

We will modify our program to party for Saturday, relax on Sunday then work any other day. We can do it like so.

let day = 'Monday';

if(day == 'Saturday'){
    console.log('Time to party');
}else if (day == 'Sunday'){
    console.log('Time to relax');
}else{
    console.log('Time to work');
}

HERE,

  • if(day == 'Saturday'){...} defines the default condition to be evaluated
  • else if (day == 'Sunday'){...} defines the second condition to be evaluated if the first condition is false.
  • else defines the code of block that should be executed if both the first and second conditions are false.

Executing the above code produces the following results

Time to work

As a lesson challenge, try to change the value of the variable day to a day like Sunday then execute the program to see what results you will get.

JavaScript print even numbers only

We will now create a simple application that prints only even numbers between 0 and 10 using the if statement.

for (i = 0; i <= 10; i++){
    if (i % 2 == 0){
        console.log(i);
    }
}

HERE,

  • for (i = 0; i <= 10; i++){...} we are using the for loop to generate numbers between 0 and 10. We will cover the for loop in the coming lessons.
  • if (i % 2 == 0){...} the if statement is used to check if the value of i is divisible by the number 2 using the modulus operator %. If the reminder is 0 then we have an even number so the condition evaluates to true.

Open the terminal and run the following command

node ifs.js

You should be able to get the following results

0
2
4
6
8
10

Summary

The if statement is used to create conditional blocks. Conditional blocks are only executed if the set condition evaluates to true. Multiple conditions can be set using the else if statement. If the condition is false and you want to take some action, then you can use the else statement.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript Functions

JavaScript Switch Statement

Leave A Reply