Friday, June 14, 2024

If, Else, Else If, and Switch JavaScript Conditional Statements

User avatar of Odhiambo Ouko

Odhiambo Ouko

7 min read·19 Reads
If, Else, Else If, and Switch JavaScript Conditional Statements

Everything you need to know about if, else, else if and switch conditional statements

In our everyday lives, we always make decisions depending on circumstances. Chew over a daily task, such as making coffee in the morning. If we have coffee beans, we can make coffee; otherwise, we won’t.

In programming, we may need our code to run depending on certain conditions. For instance, you may want your program to assign an A grade to students if they score more than 80 points or program a website to display a checkout tab on a liquor website only if the user is 18 or older. That's where conditional JavaScript statements come in. The conditions specify the code block to be executed if a specified condition is true.

Let's explore if, if…else, else if, and switch statements to understand how they are used in JavaScript.

If Statement

The if statement is the most basic conditional statement in JavaScript. This statement evaluates a condition and executes the code block within its body if the condition is true. If the condition is evaluated as false, then the code block will not run.

If Statement Syntax

if (condition) {
//code block to be executed if the condition is true

If Statement in Action

We can use the if statement to execute a given code block provided a given condition is true. For example, we can write our code to send interviewees a congratulations message if they score 75 points or more.

if (score => 75){
console.log(Congratulations! You’re hired)


Congratulations! You’re hired

If...Else Statement

What if we want to run a second code if the preset condition returns a false value? In that case, we employ the if…else statement. This statement checks a condition and runs the first code block if the condition evaluates to true. If the condition is false, the second code will execute instead.

If…Else Statement Syntax

if (condition) {
//first code block to be executed if the condition is true
} else {
//second code block to be executed if the condition is false

If...Else in Action

We can instruct our program to let users aged 24 and above create a customer account but encourage those below 24 to try the process later.

if (user => 24) {
console.log(Welcome! Proceed to open an account)
} else {
console.log(Age limit not reached. Try again in a few months!)

Ternary Operator

Although if…else statements are easy to write, there is a shorter way to write them. The shorthand Is known as a ternary or conditional operator.

Ternary Operator Syntax

Condition? Expression 1 : Expression 2;

The example above represents the syntax of a basic ternary operator. The condition to be evaluated is put before the question mark ?, followed by the statements to be executed. A colon : separates the two expressions. The entire operator ends with a semicolon. In the ternary operator, the first statement will execute if the condition is true. If it's false, the second expression will run.

Ternary Operator in Action

(passMark => 50)? console.log(Pass! Go to the next level) : console.log(Fail! Try again later);

In the above example, the program will print Pass! Go to the next level if the score is 50 or more. It will print Fail! Try again later if the score is below 50.

Else If Statement

We usually use the if…else statement when evaluating one condition. What if we want to add more conditions to our if…else statement? Simple, we use the else if statement! Unlike the if…else statement, the else if statement allows us to have more than two possible outcomes. We can also use it as many times as we want.

Else If Statement Syntax

else if  (condition) {
//Code block to be executed

Else If in Action

Let time =  ‘12:00 am’
If (time === '9:00 am') {
Console.log(‘Good Morning! Time to wake up.’)
} else if (time === ‘12:00 am’) {
Console.log(‘Good afternoon! Time for lunch.’)
} else if (time === ‘4:00 am’) {
Console.log(‘Good Afternoon! Time to go to the gym.’)
} else if (time === ‘10:00 pm’) {
Console.log(‘Goodnight! Time to sleep.’)
} else {
Console.log(‘Invalid time!’)

In the above example, the program will print Good afternoon! Time for lunch. because the time is set to 12:00 am.

Switch Statement

While the else if statements are incredible for introducing more conditions to our if…else statement, writing many statements can be cumbersome. Moreover, numerous else if statements chained in an if…else statement can be hard to evaluate. As a result, they often have readability issues and are notorious for causing errors.

Luckily, we can take advantage of the switch statement to avoid dealing with multiple if…else and else if statements. A switch statement is not only straightforward to write but also easy to read and maintain.

Switch Statement Syntax

switch(expression) {
case a: 
//code block to be executed 
case b: 
//code block to be executed 
case c: 
//code block to be executed 
//code block to be executed 

The example above shows a switch statement. A switch statement begins with a variable called a switch followed by an expression enclosed in parenthesis. Curly brackets encircling case clauses come after the expression. Each case clause ends with a semicolon to tell the JavaScript interpreter to skip to the subsequent clause.

The switch statement evaluates the expression once and compares its value against those in the case clauses. Only the code block in the case clause that matches the expression will be executed. If there is no match, the default code will run.

Switch Statement in Action

let shoeName = ‘adidasSamba’
switch (shoeName) {
case ‘adidasGazelle’: 
console.log(‘Adidas Gazelle costs $49);
case 'adidaSamba':
console.log(‘Adidas Samba costs $99’);
case 'adidasSuperstar'
console.log(‘Adidas Superstar costs $149)
case 'adidasNMD'
console.log(‘Adidas NMD costs $199)
case 'adidasCampus'
console.log(‘Adidas Campus costs $249)
console.log(Invalid option!);


Adidas Samba costs $99

Parting Shot

Throughout this article, we’ve discussed JavaScript if, else, else if, and switch statements. These statements are essential when it comes to executing specific code blocks based on preset conditions. Each of the statements plays a distinctive role and must be used correctly to achieve the desired results. In conclusion, applying best practices and avoiding common pitfalls when using these conditions to unlock their full potential is imperative.

To make Blogical work, we log user data. By using Blogical, you agree to our Privacy Policy, including the cookie policy.