Posted on February 12 - 2020 in

Shorthand Ternary Operators in Vanilla JavaScript

In a recent project I’ve been working on, I found writing out Ternary operators very tiring, especially after doing around 50 – 100 of them when checking data from an API.

They looked something along the lines of this:

(if this exists, print this, or print something else)

${person.PERSON_NAME ? person.PERSON_NAME : 'There is no name'}

It seemed stupid to me to keep having to repeat code I had already written so I started doing some research and found you could do the following:

(if person.PERSON_NAME is truthy do that, OR return a string to stay its missing…NICE!)

${(true && person.PERSON_NAME) || 'There is no name' }

Further conversations with co-workers then also made things even leaner! No need to specify the ‘true’, as checking person.PERSON_NAME will suffice.

${(person.PERSON_NAME || 'There is no name')}

And if dropping characters is really your bag, you don’t even really need the brackets.

${person.PERSON_NAME || 'There is no name'}

or

const personName = person.PERSON_NAME || 'There is no name'

Bliss…

I am going to be writing more JavaScript related posts over the coming months so if this is something that interests you, please call back again soon for more content! Thanks for reading and I hope this makes your code that little bit more streamlined!

Start your project

If you feel I can help you with web design project I'd love to hear from you. Getting started is as easy as dropping me an email to start the discussion.

Start Project