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";
}
Into this:
const dbName = env === "PROD" ? "users" : "users-dev";
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()
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! 😁
Top comments (2)
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.
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.