DEV Community

loading...
Cover image for Should we use shorthand?

Should we use shorthand?

winstonpuckett profile image Winston Puckett ・2 min read

When I say shorthand, what I mean is "statements that combine multiple lines into one." These exist in every language. For instance, the ternary operator, null coalescing operator, and optional chaining operator.

They exist because they're sometimes easier to write and take up fewer lines of code. Readability is always more important than lines of code though. Are they as readable?

Let's take the ternary operator vs its non-shorthand version:

let isFull = glassState ? "Yes" : "No";

let isFull;
if (glassState)
    isFull = "Yes";
else
    isFull = "No";
Enter fullscreen mode Exit fullscreen mode

If I'm completely honest, I like the ternary expression better. Micheal Feathers talks about the idea of "tunneling," which is having multiple nested if statements. Tunneling is bad for code readability. With a ternary operator, there's less chance for tunneling. Getting ride of all your if statements creates code that reads like a series of assignments. An assignment series is way easier for me to read than nested, scoped blocks.

On the flip side, you have to remember more syntax. One of my role models mentioned to me that unless you use the ternary operator a lot, it's hard to remember whether the true case goes first or second. I feel like this is also valid argument for readability. At this point I'm in favor of short hand because I've seen tunneling have an effect on readability and even performance. But I could be wrong, or this could be a style issue. What are your thoughts?

Note: if you're viewing this on https://winstonpuckett.com, you can scroll to the bottom and click "This post is also available on Dev." That will give you the option to respond to the post.

Discussion (1)

pic
Editor guide
Collapse
sirseanofloxley profile image
Sean Allin Newell

? has been a long friend of mine; I generally like having meaningful names and less syntax.