JavaScript

How the JavaScript ternary if and else works?

February 8, 2022

How the JavaScript ternary if and else works?

In this article we will learn how the JavaScript ternary if and else works, which are famous for their ? and :, and also how to apply this operator.

JavaScript ternary if and else cover

Hey you programmer, ok? In this article we will learn how the JavaScript ternary if/else works.

To begin with, this operator represents a normal JavaScript if and else structure in a nutshell.

That is, there is no difference between the approaches, other than the clarification of the code using the largest and most common form

The ternary if and else can be divided into the following parts:

condition ? executes if condition is true : executes if condition is false

The condition would be what we are going to compare for the if to determine if it is false or true

In normal if, this part is between parents, in ternary there is no need

Then the question mark works like a question “is it true?” and if so, enter its next condition by executing that logic

The colon (:) represents an ‘if false’, and if so, executes that logic after it

So let’s make a comparison:

// normal if
if(1 == 2) {
 console.log('true');
} else {
 console.log('false');
}

// ternary if
1 == 2 ? console.log('true') : console.log('false');

The same written comparison of the two forms, notice that the execution of ‘false’ will be given in the two structures

Since the first part of the ternary if represents condition 1 of the common if, the second part represents the else

Also notice that as the logic gets more complicated, we should choose the common approach

Because the ternary if can become very confusing, and instead of making our lives easier to write less code

It is confusing and it can create a maintainability problem

A good idea would always be to use the common form of if, in case you are in doubt which one to use

And never use it just to look like you know a lot of JavaScript or make your code more modern 😀

Use the ternary if in simple situations, the one in the example is perfect

A very small comparison with direct answers in code, without much more logic involved

Conclusion

In this article we learned the difference between the common if and the ternary if

And yet how to use each of them, and both ways can be used for the same purpose

The only difference is the code reading issue, which can be more complicated in the form of ternary if

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x