DEV Community

Cover image for Stop using ugly if's and start using ternary operators in JavaScript
Bernardo Torres
Bernardo Torres

Posted on

Stop using ugly if's and start using ternary operators in JavaScript

What is it?

1.png

As it's name suggests, is an operator that takes 3 parameters (only one in JavaScript that takes 3), the first one is the condition, the second one is what will be returned or executed if the condition is true, the last one is what will be returned or executed if the condition is false.

This definition is very vague so let's see some examples

Examples

Replacing a simple if..else statement

2.png

This can be replaced for this

3.png

Returning a value

4.png

5.png

Defining a variable

6.png

7.png

Concatenating ternary operators

You can concatenate as many as you want, but don't over use it or it will end up being a nice plate of spaghetti code

8.png

When to use it

  • When the code to execute is short

If the expression is not very simple, then it's not a good idea to use it

  • When there's no more than 1 condition

As ****I said, you can concatenate as many as you want, but it will end up being hard to read, so keep it with only one condition (sometimes 2 will be ok)

Exercises

You can make this exercises online here

https://playcode.io/new/

Replace this if...else statement

9.png

Replace this returning statement

10.png

Replace this variable definition

11.png

Solutions

Exercise 1

12.png

Exercise 2

13.png

Exercise 3

14.png

I hope this was useful to you and consider following me on Twitter, I'll be posting daily JavaScript content there

Top comments (0)