DEV Community

Ángel Blanco
Ángel Blanco

Posted on

1

#AskDev - Using JS shorthand operators for side effects?

JavaScript shorthand operators are helpful for making code more concise and readable. They let us convert code like this:

let dbName;

if (env === "PROD") {
  dbName = "users";
} else {
  dbName = "users-dev";  
}
Enter fullscreen mode Exit fullscreen mode

Into this:

const dbName = env === "PROD" ? "users" : "users-dev";
Enter fullscreen mode Exit fullscreen mode

So, basically, you can use shorthand operators to evaluate an expression into a value in fewer lines of code.

However, in some tutorials and blog posts scattered through the Internet, I saw shorthand operators being used to invoke functions. Not because they wanted to store the resulting value in a variable, but because they want to run the side effects contained in those functions. Something like this:

isUserAdmin ? storeNewData() : sendErrorMessage()
Enter fullscreen mode Exit fullscreen mode

To me, this is a weird way of using shorthand operators, because, in my mind, shorthand operators are intented for resolving into a value, not for running side effects conditionally. That syntax works anyway, but somehow it feels wrong to me.

And that's why I'm writing this post, to have a place where we can respectfully share our opinion on this. What are your thoughts? Does invoking functions with side effects through shorthand operators makes sense for you? What is your advice on this topic?

Thanks for reading / answering! 😁

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (2)

Collapse
 
theaccordance profile image
Joe Mainwaring

I have written ternary operators before that ran functions instead of returning an already-stored value, although I can't recall if I performed this operation to execute side effects.

Not sure I would today, beyond possibly a return statement, but practically speaking, it would really come down to the problem being solved.

Collapse
 
angelbt91 profile image
Ángel Blanco

As for me, if I include a function in a ternary operator, it's because it's pure and I just want the returning value - but no side effects.

I guess you're right that it depends on the problem, but anyway I see myself avoiding this kind of use in all kind of problems.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up