skull

Robert Tamayo

R
B
blog
skull

Syntactic High Fructose Corn Syrup

I recently discovered a new JavaScript feature:

let value = obj?.member?.value ?? 'defaultValue'

This isn't syntactic sugar - this is syntactic high fructose corn syrup. I got a sugar rush just looking at it.

I was a fan of the fat arrows because they solved the "this" problem in JavaScript. And I'm still a fan of many new features in ES6 JavaScript.

But this question mark nonsense is just plain abusive. As with all sugar highs, they eventually come with a crash. The crash from all the syntactic sugar added to JavaScript over the years is probably going to be the replacement of JavaScript with a newer, more modern language. It won't happen soon, but it could happen anytime in the next 2-10 years. If it doesn't get replaced, I imagine it will undergo a name change, possibly to simply "JS", joining the ranks of PHP and C as the letter-named languages.

Anyways, what does this useful bit of syntactic sugar do for us?

let value = obj.member && obj.member.value ? obj.member.value : 'defaultValue';

I'll admit the "?" in the "obj?" didn't confuse me when I first saw it. It's fairly intuitive. It's just not necessary.

My main complaints about syntactic sugar like this are the following:

  1. They make programmers get a sugar rush from feeling like they're using some kind of cool new feature, thinking they are now "advanced" programmers.
  2. They satiate programmers with sugar and keep them from growing on the meatier problems in coding.

At its core, the syntactic sugar in the beginning of the post is at best questionable in its intentions. The problem it is trying to solve is a problem that exists in languages like JavaScript and even PHP, depending on who is using it. The problem is that the data structure of an object is not known or guaranteed when members are accessed. This can result in a null pointer exception, or in JavaScript's case, the infamous "cannot read property of undefined" error.

In languages like Java, this is already guaranteed to return at least some value. It's a pain to set up, but once it is set up, you will never have to worry about checking for the mere presence of a variable - you can simply move on to checking its value.

Finally, I will add that I understand a common use of syntactic sugar is to keep the code short, readable, and tidy. But if syntactic sugar is really necessary to keep the code clean, then perhaps the algorithm itself is not as clean as one thinks? 

Putting a cherry on top of a mess doesn't clean the room.

Comments:
Leave a Comment
Submit