DEV Community

Cover image for Ternary Operators in JavaScript: Dead or Still Useful?
shelly agarwal
shelly agarwal

Posted on

Ternary Operators in JavaScript: Dead or Still Useful?

As a senior developer of 5+ years and working on multiple projects, I have seen many developers use ternary operators on a daily basis, but is it worth using every single time? 🤔

I am quite comfortable using it to be honest, it is really simple to use and easy to write but there are many cases when we must avoid it in order to avoid bugs in a complex condition.

Example 1.

Use case:
There is only 1 condition.

const flashStatus = `Flash ${buttonType === 'flash' ? "on" : "off"}`
Enter fullscreen mode Exit fullscreen mode

Any problem you can see? ☝️
None

Example 2.

Use case:
If multiple conditions are present.

const shutterCallBack =
  selectedOption === 'Video' ? (isRecording ? stopRecordingVideo : recordVideo) : takePhoto;
Enter fullscreen mode Exit fullscreen mode

Any problem you can see? ☝️
Yes

  1. If any new team member joins the team, they won't know what the condition is doing and they can actually break the code by adding more conditions if they don't understand it in the first place.
  2. It is really hard to debug the condition if any issue occurs because you need to identify each condition output before you make any changes.
  3. Maintainability Issues of course.

What is the solution then? 💡

  1. Keep your conditions simple and easy to understand.
  2. Use either switch statement or if/else in order to maintain these dependent conditions
  3. Add necessary comments to provide context what these conditions are doing.

You can avoid nested ternary operators and change the condition like this ->
1. ✔️ If-Else Statements (More Readable)

let shutterCallBack;

if (selectedOption === 'Video') {
  if (isRecording) {
    shutterCallBack = stopRecordingVideo;
  } else {
    shutterCallBack = recordVideo;
  }
} else {
  shutterCallBack = takePhoto;
}
Enter fullscreen mode Exit fullscreen mode

OR

2. ✔️ Object Mapping (When Dealing with Categories)

const shutterActions = {
  Video: isRecording ? stopRecordingVideo : recordVideo,
  Photo: takePhoto,
};

const shutterCallBack = shutterActions[selectedOption] || takePhoto;

Enter fullscreen mode Exit fullscreen mode

Ternary operators are obviously not dead but you need to make sure use these only for precise conditions and not on multiple or complex conditions.

What do you think? Comment your thoughts..

Top comments (0)