DEV Community

Cover image for If, Else, Else If, and Switch JavaScript Conditional Statement
Odhiambo Ouko
Odhiambo Ouko

Posted on

If, Else, Else If, and Switch JavaScript Conditional Statement

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
}
Enter fullscreen mode Exit fullscreen mode

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! Youre hired)
}
Enter fullscreen mode Exit fullscreen mode

Output

Congratulations! You’re hired
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

If…Else Statement 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!)
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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!)
}
Enter fullscreen mode Exit fullscreen mode

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 
break;
case b: 
//code block to be executed 
break;
case c: 
//code block to be executed 
break;
default:
//code block to be executed 
}
Enter fullscreen mode Exit fullscreen mode

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);
break;
case 'adidaSamba':
console.log(Adidas Samba costs $99);
break;
case 'adidasSuperstar'
console.log(Adidas Superstar costs $149)
break;
case 'adidasNMD'
console.log(Adidas NMD costs $199)
break;
case 'adidasCampus'
console.log(Adidas Campus costs $249)
break;
default: 
console.log(Invalid option!);
break;
}
Enter fullscreen mode Exit fullscreen mode

Output

Adidas Samba costs $99
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (5)

Collapse
 
efpage profile image
Eckehard • Edited

Ternaries can result in readable code if you use them carefully, but you should not overuse the concept. This is the common use and it can be ok to call a function from inside a ternary.

let a = (animal == cat) ? "cat" : "dog"; // OK
let a = (animal == cat) ? "cat" : getName() // OK
Enter fullscreen mode Exit fullscreen mode

But there are several ways that make your code hard to read with ternaries, and I would recommend to use if/else instead. Here are some bad examples:

Function test(condition){
     condition ? return : {
         ....
     }
}

let a = (animal != mouse) ? (animal == cat) ? "cat" : (animal ==  dog) ? "dog" :  "unknown"

condition ? console.log(a) : return
Enter fullscreen mode Exit fullscreen mode

Even though it is possible, ternaries are not meant to be used for flow control. This often makes your code hard to read. See the comparison, which is much easier to read:

   if (condition)  console.log(a) 
   else  return
Enter fullscreen mode Exit fullscreen mode

If you want to use nested ternaries, there is a nice scheme to use:

let animal = 2
let a = 
    animal == 1 ? "cat" :
    animal == 2 ? "dog" :
    animal == 3 ? "mouse" : "unknown"
Enter fullscreen mode Exit fullscreen mode

here you put the nested ternary only in the false branch.

The use of switch / case / break is very verbose in JS. Some people recommend to use this scheme instead:

function test(val){
    switch(val){
        case 1: return "cat"
        case 2: return "dog"
        case 3: return "mouse"
    }
   return "unknown"
}
Enter fullscreen mode Exit fullscreen mode

Switch is not very often used, as in many cases it is much shorter and faster to use objects instead:

function test(val){ // verbose function
   let options = { 
        1: "cat", 
        2: "dog", 
        3: "mouse" 
   }
   return options[val] ?? "unknown"
}

// shortened, but less reable forms

function test(val){ 
    return {1: "cat", 2: "dog", 3: "mouse" }[val] ?? "unknown" 
} 

// -> Arrow function
const test = val => ({1: "cat", 2: "dog", 3: "mouse" })[val] ?? "unknown"

// result
console.log(test(1)) // => cat
Enter fullscreen mode Exit fullscreen mode
Collapse
 
odhiambo_ouko profile image
Odhiambo Ouko

Thanks for the input. I really appreciate it!

Collapse
 
martinbaun profile image
Martin Baun

Very well written. These types of writeups are very important for the people that do need them especially since some programming languages don't even have "switch" statements at all

Collapse
 
odhiambo_ouko profile image
Odhiambo Ouko

Thanks for your kind words and appreciation!

Collapse
 
lenangetai_senila_42ac3ea profile image
Lenangetai Senila

Awesome article Odhiambo!