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"}`
Any problem you can see? ☝️
None
Example 2.
Use case:
If multiple conditions are present.
const shutterCallBack =
selectedOption === 'Video' ? (isRecording ? stopRecordingVideo : recordVideo) : takePhoto;
Any problem you can see? ☝️
Yes
- 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.
- 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.
- Maintainability Issues of course.
What is the solution then? 💡
- Keep your conditions simple and easy to understand.
- Use either switch statement or if/else in order to maintain these dependent conditions
- 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;
}
OR
2. ✔️ Object Mapping (When Dealing with Categories)
const shutterActions = {
Video: isRecording ? stopRecordingVideo : recordVideo,
Photo: takePhoto,
};
const shutterCallBack = shutterActions[selectedOption] || takePhoto;
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)