Ternary Operator in JS: Everything you need to know

Ternary Operator in JS: Everything you need to know




What is Ternary?

Ternary Operator is a javascript operator which is available across browsers since July 2015. It is a shorthand alternative for if/else statements. This operator is widely-used in different programming languages like Java, C, Python but our focus in this article will be on javascript.

Let’s check out the general syntax of ternary operator.

condition ? ifTrue : ifFalse
Enter fullscreen mode

Exit fullscreen mode

As you can see from the example above, ternary operator replaces if and else statements, accordingly, with ? and : symbols. The condition which is on the left-hand side of the question mark will be checked. If it is true, first expression which is between the ? and the : mark will be executed. If it’s false, last expression which is written after the : symbol will be executed.



How it works?

In order to understand how ternary operator works, let’s compare it with the regular if/else statement.
The Javascript code below, will log a string to the console, conditionally.

let a = 10

if(a == 10){
    console.log("Variable is ten!")
}else{
    console.log("Variable is not ten!")
}
Enter fullscreen mode

Exit fullscreen mode

Now, let’s re-write this code using ternary operator.

let a = 10
a == 10 ? console.log("Variable is ten!") : console.log("Variable is not ten!")
Enter fullscreen mode

Exit fullscreen mode

Ternary operator in this code block conditionally logs the string as the way we intend. But there is a better way to write this statement.
Ternary operator not only executes the expression but also returns the value. Thus, instead of using operator to handle two different console.log expressions, we can write the statement in a way that it handles two different values which is in the one console.log statement.
For example:

let a = 10
console.log(a == 10 ? "Variable is ten!" : "Variable is not ten!")
Enter fullscreen mode

Exit fullscreen mode

The output of this line will be exactly same as the other ternary expression we’ve write before. But this code is more compact and easy-to-read.

We can use ternary operator to assign values to variables conditionally. Let’s check out an example with regular if/else statements, then write it again using ternary.

let a = 10
let b
if(a === 10){
    b = a * 5
}else{
    b = a * 2
}
Enter fullscreen mode

Exit fullscreen mode

If a is 10, the code block will multiply it by 5, else it will multiply the variable with 2 and in both cases, will assign it to b.
The alternative using ternary operator will be just like following:

let a = 10
let b = a === 10 ? a * 5 : a * 2
Enter fullscreen mode

Exit fullscreen mode

As you can see it is more convenient to write a single line code for basic operations like this.



Nested Conditions

Sometimes we have to use more than one if/else conditions within each other. Ternary operator can be utilized to chain conditions.

let a = 5
if(a === 1){
    console.log("1")
}else if(a === 2){
    console.log("2")
}else{
    console.log("a is not 1 or 2")
}
Enter fullscreen mode

Exit fullscreen mode

This chaining of condition which is shown above can be represented using ternary operator in the following way:

let a = 5
console.log(a === 1 ? "1" : a === 2 ? "2" : "a is not 1 or 2")
Enter fullscreen mode

Exit fullscreen mode

As you can predict, this can get very messy easily. That’s why using ternary operator in complex conditional statements is not required.



Ternary in React

If you have build a React application before, you probably know that conditional rendering is an important topic. Ternary operator makes this operation easier. Let’s check out an example from the official page of React.
This is the regular way of writing the statement:

if (isPacked) {
  return <li className="item">{name}</li>;
}
return <li className="item">{name}</li>;
Enter fullscreen mode

Exit fullscreen mode

And this is the same statement, but using ternary operator.

return (
  <li className="item">
    {isPacked ? name + '' : name}
  </li>
);
Enter fullscreen mode

Exit fullscreen mode

As you can see it looks much more better. Thus, sometimes it is cleaner and better approach to write statements with ternary, especially while working with React. But in some cases, ternary operator can make code even harder to read.

In which other situations, do you think, we have to use or avoid ternary operator? Please let me know your thoughts in comments!

Thank you for reading.
Please check out these links for further reading.



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.