DEV Community

Cover image for Conditional Operators
Kulsum Shaikh
Kulsum Shaikh

Posted on

Conditional Operators

Today, we will be discussing two types of conditional operators. The first one is a if else statement and the second is the ternary operator.

Let's start with the if else statement's syntax:

if (condition1) {
     statement1

} else if (condition2) {
     statement2
} else {
     statement3
}
Enter fullscreen mode Exit fullscreen mode

Note: You don't have to have two different conditions. It can also be done with just an if statement and an else statement (without an else if).

The condition in the if statement can be any condition that can be truthy or falsy. Then, the statement states what will happen if that condition is met. Then, you can either add another condition or just have a general statement (which will be put into else) that will happen if the first condition is not met.

Now, let's try it out!

function ifStatements(x) {
     if ( x >= 15) {
          console.log("I'm greater than 15!")
     } else if (x > 10 && x < 15) {
          console.log("I'm between 10 and 15!")
     } else {
          console.log("I'm everything else!")
     }
}

ifStatements(8) // This gives "I'm everything else!"
ifStatements(20) // This gives "I'm greater than 15!"
ifStatements(12) // This gives "I'm between 10 and 15!"
Enter fullscreen mode Exit fullscreen mode

Based on what x had equaled, the console.log gave us different answers!

Now, let's look at ternary operators! Personally, I like ternaries more because of two things: It's short and it can be done in one line!

The syntax for ternary operators looks like this:

condition ? expressIfTrue : expressIfFalse
Enter fullscreen mode Exit fullscreen mode

The condition in a ternary is a condition that will either be truthy or falsy (just like an if statement). The first expression will be shown if the condition is truthy. If the condition is falsy, the second expression will be shown.

Let's look at how it works:

function ternaryOperators(isHappy) {
    return (isHappy ? "Yay!" : "It's okay to feel upset!")
}
console.log(ternaryOperators(true)); // "Yay!"
console.log(ternaryOperators(false)); // "It's okay to feel upset!"
Enter fullscreen mode Exit fullscreen mode

Based on whether isHappy was true or false, the console.log gave us the two different strings!

I think Ternary Operators are better if you want to check one condition while if statements are better if you have multiple conditions that you want to check! Both are very useful and help make JavaScript easier to use!

Top comments (0)