Using the Ternary Operator to Rewrite an If-Else Statement in JavaScript

Posted by

JavaScript: Rewriting an if-else statement using the ternary operator

JavaScript: Rewriting an if-else statement using the ternary operator

JavaScript offers a convenient shorthand for writing simple if-else statements using the ternary operator. This allows you to condense your code and make it more concise. Let’s see how to rewrite an if-else statement using the ternary operator:

Suppose we have the following if-else statement:

        
            var isTrue = true;

            if (isTrue) {
                console.log('The condition is true');
            } else {
                console.log('The condition is false');
            }
        
    

We can rewrite the above if-else statement using the ternary operator like this:

        
            var isTrue = true;

            var message = isTrue ? 'The condition is true' : 'The condition is false';
            console.log(message);
        
    

In the above code, we first declare a variable ‘message’ and assign it the result of the ternary operator. The ternary operator consists of three parts: the condition (isTrue), the value to be returned if the condition is true (‘The condition is true’), and the value to be returned if the condition is false (‘The condition is false’).

Using the ternary operator in this way can help make your code more readable and concise. It can be particularly useful when you have simple if-else statements that do not require a lot of logic.

So next time you need to write a simple if-else statement in JavaScript, consider using the ternary operator for a more streamlined approach.

0 0 votes
Article Rating
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@CoderBelal
8 months ago

Which theme do you use?

@aghakarim_
8 months ago

Cool 🎉

@duyonmimix6986
8 months ago

Is it posible on other languages, such as python, php?????

@user-gw4df2de3k
8 months ago

eslint on my project doesnt allow nested termary operators 😢

@muthuraja8156
8 months ago

I feel if More than two conditions, we can use if else condition is better

@fasteditsyt
8 months ago

Yes Sir you are so cool! Thank you!