Syntactic High Fructose Corn Syrup
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.
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:
- 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.
- They satiate programmers with sugar and keep them from growing on the meatier problems in coding.
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.
Leave a Comment