Conditional Statement in JS — with examples

Siddharth Rastogi
3 min readMar 30, 2022

In this article, we will learn about the Conditional Statement in Javascript (JS). Whenever you write a code, there comes a time that you have to perform actions based on certain conditions. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform the right actions.

Conditional statements allow us to make such decisions based on a condition in JavaScript. If the condition is true, we can perform one action, otherwise, we can perform a different action.

We have different types of conditional statement in JS, which we can use according to the requirement and logic. Okay, so let’s start and understand them with examples.

Table of Contents

  1. if statement
  2. else statement
  3. else if statement
  4. switch-case statement

What is Conditional Statements?

A conditional statement is an essential part of any programming language. It is used to execute one or more statements based on a particular condition. Each condition works on a Boolean value that can be true or false.

For example, if we have some spare time, we have to decide what to do, whether to rest, watch something, call someone or maybe do something productive. So, it allows us to make such decisions based on a condition in JavaScript.

How many types of Conditional Statements in JS?

We have four types of conditional statements in JavaScript:

1. if

2. else

3. else if

4. switch

So if-else and switch-case both allow us to make these decisions based on a condition. Let’s discuss them one by one.

if statement

if-else statement takes a specific condition and checks whether the condition is true or false. If the condition is true, then the if statement executes a specific code block.

Let’s take an example, in the below piece of code, the age is 15 which is less than 18 so the condition is true the output will be executed.

else statement

In the above example, when I changed the age to 20, then the 1st condition is not met in that case i.e the condition is false, then the else statement executes a different code.

If you want to read the full post, then reach out at here SidTechTalks. I have explained in details. I hope you like it, and if you like it please share with your friends.

Thank you.

--

--

Siddharth Rastogi

I am a full stack developer, I have an expertise in Web Development. I write tech stuff and share my knowledge with others through blogs & articles.