DEV Community

Jesús Jiménez
Jesús Jiménez

Posted on

Use more ternary operators!

First of all, I'm sorry if my English is bad, but I want to try to share my programming tips.

We have a lot of code where we are using a lot of ifs but, when it if can be replaced by other kind of instructions in javascript (and another languages) we should use them and, what is exactly a ternary operator?

A ternary operator is like an if-else, it don't have more else and its necessary use two returns but, I will show you how to use it.

let num = 10;

console.log(num > 10 ? 'Greater than 10': 'Less than 10');

Yeah, it is so strange if it is your first time seeing a ternary operator but, if you see this it is so easy to use and its more useful that try to print the same using an if and an else. We three steps to get a ternary operator, first we have a condition where we can use conditions lice <, <=, >, >=, ==, != equals and more, and next we have the two values that return true (first value) and false (second value).

Here is an example but using if-else.

let num = 2;

if (num > 10) {
   console.log('Greater than 10');
} else {
   console.log('Less than 10');
}

If you see the example we can reduce a lot of code and if we use this ternary operators we could have a clean code.

The ternary operators can be use when we try to send a value to a function or return another. Here is an example.

let sleep = false;


function sleepOrNot(sleep) {
  return (sleep ? 'You need to sleep': 'Hello world!');
}

console.log(sleepOrNot(sleep));

// expected out: 'You need to sleep'

All the examples are so simple but when we use this operator with our projects we can have clean code and make it more understandable for the rest of our teammates or even for ourselves.

If you need some help and you don't have idea when you need to use this operator download the extension called Javascript Booster and it helps you to reduce an if-else and a lot things more. Read the docs and try to use it :)

Top comments (4)

Collapse
 
mzaini30 profile image
Zen

Use Javascript for syntax highlighting in your post. Like this:

let num = 10;

console.log(num > 10 ? 'Greater than 10': 'Less than 10');

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Someone should write a Markdown tutorial 😄

In VSCode, I really recommend markdownlint.

(I also know that there is an Information icon down there.)

Collapse
 
asasced profile image
Jesús Jiménez

Thank you so much, I didn't know that :)

Collapse
 
mzaini30 profile image
Zen

You're welcome Friend