Javascript Ternary Operator for the win

Meet Pandya
2 min readAug 5, 2022

--

So, this title could have also said Typescript Ternary Operator as it is supported by both the programming languages.

Ternary Operator is a short-hand form to write a simple If/Else block.

The below example is a simple way of using the ternary operator which involves a ? and :

We have two integer variables & we are trying to decide if the speed is above the limit then return True or return False

With a ternary operator, everything that is before the ? is the conditional part. Whatever is between ? and : gets executed if the condition is true. If the condition is false, then whatever is after : gets executed

Below is what you would have of the previous code without using a Ternary Operator

Moral of the story is, Ternary Operator can make your basic If/Else blocks look a lot cleaner and simpler to read.

Don’t get into the habit of using Ternary in complex situations or nested Ternary

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response