Sh*tpost: can we stop saying "syntactic sugar"?

jen chan on January 18, 2019

"Syntactic sugar": After self-studying what seems like a narrow and ever-changing field for four years this term keeps rearing its head. I'm not us... [Read Full]
Editor guide

It's called syntactic sugar because it doesn't introduce any substantial new feature to the language, it's just a sweeter syntax.

So yes: destructuring and += are examples of syntactic sugar because you could write it in the longer, less clean form, and it would be equivalent.

As a side note, sometimes the verb "to desugar" is used to mean "to turn into the equivalent syntax without sugar" As in this example sentence:

a += b desugars to a = a + b

Async/await is not an true example of syntactic sugar, it's an entire new feature in the language. You can re-write async/code to use then/catch handlers but it's much more than a simple syntax transformation, it's a re-write.

In conclusion, it's called "sugar" probably because it implies it's something you sprinkle onto the language syntax to make it easier, but not a whole new set of features. Under the hood, syntactic sugar could be implemented as a transformation of the syntax tree, so the runtime engine may not even need to know about it.

And I agree with the "diabetes" argument: too much syntactic sugar isn't good, it can definitely be taken too far when it makes code harder to read instead of easier to read.


Thanks for your response.

In terms of async/await, and then/catch. When do you feel is a good time to use either?
For asynchronous operations, I have most often resort to fetch and then/catch. Not a very varied vocabulary.


@jenninat0r , It might just be a typo, but I think you meant async/await syntax vs. promises which use then/catch syntax to chain operations (with .catch(cb) being used for error handling). Not try/catch.

In the case of async/await, you'd just use normal try/catch syntax around your await calls for error handling.

Both are used to accomplish the same thing, so I'd say which one you use is a matter of preference. Promises are very similar to monads (although technically they don't quite qualify as such), and I suspect that promises were developed to kind of support a functional style of programming (everything stays in the context of a promise). On the other hand, async/await is designed to make the code look like ordinary imperative code, only asynchronous.

I could be wrong, but I would say whichever one is easier for a team to work with is the one they should use.

Yes it was a brain fart. I’m in the ‘then/catch’ camp !


To me it seems easier to do error handling when using async/await vs then/catch. Most of the times you need an extra try/catch when you're doing then/catch, but when using async/await both sync and async exceptions are caught.


You are incorrect about async/await in javascript (and actually in every language that I've looked into the implementation). It is internally just unrolling promises yielded from a generator function.

I was doing this with my own code and libraries like co for years before async/await became popular. I think even q had a version of the concept. The experience was almost identical to async/await - you just had to use do co(function * () { ... }) instead of async function() { } and yield instead of await. The fact that it was such a simple swap-in was one of the major reasons that I and many others opposed the introduction of those features.


async/await is not equivalent to using promises. It provides fundamentally different functionality by wrapping promises with a generator. It is important to recognize the difference, because it affects error handling in a significant way.


const doSomething = () => {
  somethingElse().then(() => anotherThing());

In this example, if somethingElse() or anotherThing() throw an exception, we would want doSomething() included in the stack trace, since that's where somethingElse() and anotherThing() are called from. In order to do that, the Javascript engine has to capture and store a trace of the stack where doSomething() is called before moving into somethingElse() since it will be inaccessible after somethingElse() is on the stack. That operation consumes both memory and time.

Now consider:

const doSomething = async () => {
  await somethingElse();

Using await, there is no need to copy and store the current stack context before the execution of somethingElse(). Simply storing a pointer from somethingElse() to doSomething() is sufficient: during the execution of somethingElse(), doSomething() is still on the stack with its execution suspended, so it's available from inside somethingElse(). If somethingElse() throws an exception, the stack-trace can be reconstructed by traversing the pointer. If anotherThing() throws an exception, the stack-trace can be reconstructed as normal, because we are still within the context of doSomething(). Either way, capturing and storing a stack trace in memory before doSomething completes is no longer necessary, and constructing a stack-trace only happens when its necessary, i.e. an actual exception was thrown from somethingElse() or anotherThing().


It's only usually used for things added to the language later in my mind.
for could be "desugarred" into while for example, but we don't call for sugar in the normal run of things.

It's all a bit murky.


Interesting points, most of which I hadn't thought too deeply about before. I do find "syntactic sugar" has become a weasel word, much like "scripting language" is. It is often deployed as a way of belittling the value of a language's syntax choices.

I suppose by some interpretations, everything is "syntactic sugar" because we're not writing in binary. By even Landin's original usage, it's just a symbolic abstraction, and all modern languages are effectively symbolic abstractions.

While I like the idea proposed in the comments that "syntactic sugar" adds no actual features, but rather just makes the code easier to read and write, one could make the counterpoint that we never actually have "new features" by the truest definition of the term. We can replicate all imaginable behavior in assembly/binary, desugared, but nearly all of it would be too complicated for direct replication to be practical.

Perhaps some developers just use the belief that they write in a more "sugar free" language as a form of self-aggrandization, a la "real programmers use butterflies," but I'd counter that making one's own workflow deliberately harder with no actual gain is considerably more obtuse than using "syntactic sugar". (Bear in mind, that's coming from someone who spends a phenomenal amount of time doing bare-metal memory management in C and C++.)

In other words, it would be tremendously stupid of me if, for no other reason than to avoid "syntactic sugar," I built an application in C that could have been written to identical spec and goals in Python, given the fact I know both languages. Yet some coders I know will do exactly that.

By the way, that does not include projects for continuing self-education; knowing languages like C gives one a deeper working understanding of, not to mention an appreciation for, the abstractions that exist.

By the way, I'm not sure your particular choice of title is entirely constructive, mainly because you shouldn't devalue your own post by labeling it such. By the same token, you're not a bird brain or a knucklehead. Belittling yourself and your work is only useful for destroying your self-esteem and crippling your own growth.

"Humility isn't thinking less of yourself, it's thinking of yourself less." -C.S. Lewis

Never confuse a lack of knowledge with a lack of intelligence. A birdbrain couldn't have even written this article.


Thanks for your response, and you've given me a lot to think about in regards to it as an actual compsci term! And yeah, if we consider the scale and complexity of certain applications, sugar makes sense due to not repeating oneself, cutting down lines of code, etc. I think my disgruntlement was over the blurriness of its meaning. It could be a feature, a transpiling/intermediary syntax on a framework, it could be a bunch of new syntax in a newer version of a language... etc. And coming from a learner's perspective, it seemed like jargon that was a hindrance to understanding exactly what that "add-on sidedish" of a syntax did.

Re: self-effacement
On the same lines of logic, being able to talk about code doesn't mean I know how to code proficiently. But I'm definitely enjoying reading more about the details of how JS works and making quantum leaps in my own way.

I know where I stand given the general response and performance on the job. There's been a bunch of failures in the last two years, but I enjoy coding. I believe intellectual vulnerability is important for learning and creating good vibes. In case I seem to devalue myself too much I have salary negotiated and tried to prove myself as much as I could that I was a valuable member in previous positions. Previous experience has made me feel inauthentic when acting confident or burying insecurity in addition to trying super hard to fit in various work cultures. Guess time will tell. In a few years I may regret this style of writing. I appreciate your encouragement and know what you mean though--used to teach/mentor art students. Hated that they felt nerves over explaining their relatively young practices. I'd be like, "It's art, not brain surgery. You're doing it! Who cares what kind of artist you are?!"


I completely understand where you're coming from about feeling inauthentic. That's actually called "imposter syndrome", and talking down about yourself feels like a cure. In reality, self-debasement will make the imposter syndrome worse.

I suggest you adopt a different line of describing yourself. (This is the one I use myself):

  • Be as honest about your strengths as your weaknesses. For example: I am an expert in C++ memory management, but I have no skills in machine learning. I am fairly good at designing vector-based logos, but I cannot draw a decent stick figure to save my life. Keep your positive and negative self-statements in balance.

  • Own your mistakes, only allow yourself to apply negative terms to what you did, not who you are. For example: I once a wrote a scripting language in ActionScript 3.0 using regular expressions. It was terrible, slow, and I made sure to destroy that source code so it would never see the light of day again. I say: "the language design sucked." I don't say: "I suck at language design."

  • Avoid exaggerations. I'm a quantitatively verified expert in some areas of coding, but pretty dismal in others. Thus, I wouldn't say "I'm a programming expert" (unqualified), as that'd be an exaggeration; I'm only an expert in certain things. But I wouldn't say "I'm a mediocre programmer", because I've written some definitely non-mediocre things.

By the way, programming is art, so everything you told your students applies here. It's programming, not brain surgery. You're doing it! Never allow yourself to say "I'm not a real programmer." If you've written code, you're a real programmer.

Be honest about what you have yet to learn, but be just as honest about what you can do. Keep praise and criticism of self in balance.

Thanks for spreading the positivity man! Wish more people had healthy self esteem practices on the interwebs. You are doing good things. Hope you have a great day!


P.S. May I recommend you reace the #unpopularopinion tag with #healthydebate? This fits right into that category, and again, I wouldn't devalue your opinion so much!


I included #unpopularopinion as a reference to the same hashtag on twitter. I'm going to add #discuss.

"Sh*tpost:" was my attempt at a linkbait title. I always hope to get people reading and responding hehe.

It's highly unusual that somewhere on the internet you can actually post an opinion about dev and not be ignored, downvoted or dogpiled on like on StackOverflow, that when someone new makes a post with a strong opinion, traditionalists aren't coming in hoards to tear them down. The devTO blog is super special for this kind of environment. shout out to @thepracticaldev

I imagine that self effacement is a self-protective coping mechanism in addition to my inclination towards new sincerity (authentic, earnest, gratuitous expression).

SO aims to be factual and reusable. It can be intimidating to be downvoted as a new user, it has certainly been for me, and non-verifiable and incomplete information from experts can certainly still be useful, but the value of SO as a whole is increased because of its strict policies. Dev.to might be more beginner-friendly but is often wildly inaccurate.

Unrelated: I think you hit the nail on the head with "sh*tpost" in terms of clickbait :P


This reply is great on so many levels!


Your website is 10000/10 AMAZING by the way. If you haven’t already seen it, you might like this wab.com


I'm a huge fan of syntactic sugar in C# - but its always there. In JavaScript, support is dependent on the environment unless you transpile and polyfill all of your code all of the time (at least for example the spread operator)

C# example (14 lines to 1 with proper linting):

public string Property { get; set; }

Is syntactic sugar for:

private string propertyField;

public string Property
        return propertyField;

        propertyField = value;

Well I guess coffeescript is complete syntax caramel then!

That is a really clear example, thanks!


lol "complete syntax caramel"... I love it! I'm using that!

I've also used the term "syntactic saccharine" to describe bad sugar. Causes cancer of the semicolon.

I like how CoffeeScript turns this

x?.y?.z = 3

into this

if (typeof x !== "undefined" && x !== null) {
  if ((ref = x.y) != null) {
    ref.z = 3;

Short, sweet, and succinct. Now that is a delicious syntactic caramel!

Those are great. Included with C# 6, probably copied from coffeescript.


If I recall correctly, the C# language spec or some of Microsoft's engineers made the property syntax above as a means by which to entice VB programmers to start using the language. This was "sugar" for get_Property() and set_Property(string value) respectively, a common naming convention in Java for functions that represent properties. Great article by the way and I appreciate the positive vibes.


Syntax sugar is a sweet way to say "This code is not giving any extra business value".

For example, JSX is for to write the DOM, so instead of writing the dom, we write the JSX that writes the DOM. What is the extra value?. Fast reading the dom?. We could do it with variables. Fast writing the dom? Well, all of them write the DOM but JSX adds a new layer so it's slow.


No, I don't think you can say syntactic sugar doesn't give any business value.

Can you write the shorter form more quickly and maintain it easier? There's your business value.


I didn't think about the performance tradeoff JSX might introduce. I don't have a huge understanding of React (attempted to learn twice while working fulltime and turned to vue eventually. Heard of its virtual DOM).Did you mean it is slower than other frameworks or... than writing the same thing in JS itself?


The concept of virtual dom is cool. However, it is not really usable for every single application.

For example, let's say a classic web: HTML + JQuery. I draw the HTML (that is fast) then I call JQuery to modify the DOM. If the changes are minor, then modifying the DOM directly is quite fast, for example reading field of a form.

The alternative is to create a JSX and to use React to render the HTML (so the browser is doing an extra job). And, if we want to modify the dom, then we access the virtual dom. This virtual dom accesses to the dom, so we are adding a new layer again.

JSX shines when we need to modify intensively the DOM.


Hum...I supposed the term is more relevant to verbose languages. For example, the term is useless in Ruby where almost anything can be written in three different ways.

Taking your example of React, JSX is not a feature of JS. It's a feature of the development environment most React users work in. (You can write pure React code without transpiling but you won't have any JSX). So, in that case, it still makes sense.

defer( comment.conclusion )


But wouldn't it be more accurate to call JSX a transpilation source?

It's nothing more than React.createElement() under the hood and when run through Babel, that's what you get. It transpiles down to JavaScript.

Sugar, to me anyways, has always been a part of the language itself, but a more friendly way of writing something. The compiler usually rewrites it in its original statement. Like the :: in Java. The :: is not really a java feature, it just makes thing simpler.


reduce(Math::max); gets transformed by the compiler into reduce((int left, int right) -> Math.max(left, right));. The :: is not read by the JVM, but it is replaced by its Java equivalent by the compiler.


Maybe I'm being pedantic, but I think a sugar would be something the language itself accepts. JSX is not accepted by any JavaScript engine without a 3rd party tool.


Being pedantic is good for exploring semantics hehe.

And I was being petty in complaining about 2 seconds in an "Intro to React" video in 2016. I agree that it's more intermediary. I came away with the impression that I had to learn an intermediate syntax that was not-JS,not-HTML in order to use React, and it would be transpiled back to ES5 anyway. Maybe it's not necessary anymore and React has changed a ton since--I don't use it but I'm going to get around to familiarizing myself after I cover more JS fundamentals.

Out of curiosity I just looked: thepracticaldev.s3.amazonaws.com/i...

It's all because of IE I guess. I've derailed. Thanks for entertaining my rant.


True, I only have 1 language to evaluate how that term is used and this could be helpful in a compare/contrast sense.


I always interpret syntactic sugar as "unnecessary shortcuts". So a third party library that adds a layer of convenience functions on top of AutoLayout, for example. If all I think it's doing is providing some syntactic sugar, then I'll probably stay away. Why save some keystrokes and build up crutch with some shortcuts when I can just do it the "right way"?

There are so many third party libraries who's sole purpose is to decrease the verbosity of your code, and I don't really see "typing too much" as a problem I have.


I'm prone to take your approach of writing in plain and simple ways before I embark on sprinkling. The latter is for refactoring or a second or third pass at something. Most of that is because I know i have a primitive handle on the language and it's better to go tried and true instead of trying to use every little thing just because I found out about it. But reading other folks code or tutorial docs also kind of clue me in on how often people use a certain something.


You are exactly right that constructs like ++ and destructuring are syntactic sugar.

The whole idea of "syntactic sugar" is that it is something that is never required to write your code, and is 100% able to be done within the other constructs of the language. But if you find yourself needing to that other "other way" frequently, you can write a lot less code by using this "sugar" to write less code and have each line of the code you write be more meaningful.


I agree with you Jen in the sense that we might abuse of extraordinary key words to speak about simple things.

When we hear "syntactic sugar", we stop at syntactic and think of something very elaborated, a very mature concept, then moving on sugar we stop again and think "wait what, is it not supposed to be a serious concept? Why sugar? What does it means?".

Developers are some funny species, trying to put a little bit of spices on their life (you got it, spice, sugar,...) to make things more digest I guess.

But again, I think sometimes things are amazingly more obscure than they were meant to be.

One of my favorite new syntactic sugar is the PHP `$_SERVER['REFERER'] ?? $previousPage ?? null;", which means nothing if you are not aware of the null coalesce operator. Can't wait to see it in Javascript!


I recently had an idea for a t-shirt for women with "syntactic sugar" on it - sort of an appropriation of the trend a few years ago to have "angel" on the back of your sweatpants. Anyway, when I googled to see if I could buy one someone else designed, I found one that said, "Assembly is just syntactic sugar." Probably the most extreme (and I assume ironic) assessment of what you express here.


HAHA oh yeah a couple of my friends recall now and again the 2000s "Juicy" sweatpants. That trend had spread to Victoria's Secret Pink underwear and I recall being kind of distrubed some time back teen underwear seemed to be lined with catcalling phrases.

I don't know Assembly so that statement is lost on me... but lol Date.now() + createdOn... I am finally comfortable with people saying "syntactic sugar" after hearing all the contexts it's used in. I still wish we all agreed on a semantic definition like "shorthand for doing the same thing".


Assembly is just a step above binary, so VERY low level - the lowest you can get without using ones and zeroes. It's not particularly human friendly - well I guess it is compared to ones and zeroes. :-) So technically it IS syntactic sugar, but not in the way people mean to use that phrase. I guess it implies people who complain about syntactic sugar might as well be using ones and zeroes if they're so above whatever they're talking about.


This entire post is Semantic Seasoning, which means it's about changing the way things look without changing their functionality, and it's really salty.

I think the phrase "semantic sugar" exists to let use know that something only exists for that reason. If someone introduces a way of abbreviating the language without changing its functionality, that's SS. It's bad because it's not backwards-compatible and doesn't add anything new.

Your example of += is semantic sugar, but because it's been in languages for donkeys' years it's ok. If you were to take a language without that symbol (Python?) then introduced a mod to allow it, that'd make a lot of people happy. But it would require everyone else to use the same mod (whether it be a library or a change to the interpreter) and that mod would be seen as unnecessary by a lot of people.

I think that's the difference. SS is a problem when it makes unnecessary things necessary.


Yes, I never cared much for it. It doesn't add anything useful to the conversation and it will most likely be used with a condescending tone by someone who's job is to lecture you on things you already know.


I don't use the term myself, I call it by the feature name (like async/await), "the new syntax for _", or "the improved syntax for _." I just call it what it is instead of trying to dress it up.

I think it is one of those terms that is picking up in usage recently, especially in the JavaScript community. I think that leads to a tendency of muddying the original intent and having it be applied to everything new added to a language.


I think we need some syntactic sugar to describe syntactic sugar! I love syntactic sugar so much, but there's currently no syntactic sugar to show off my love for that which is syntactic sugar! :trollface:


"It's just Syntactic sugar" says "There is another way to do this in the language already". This statement is only valuable if used in the form "It's just Syntactic sugar for ...". This explains new syntax in terms of the verbose version a person already understands. That has valuable. It's like saying "Don't panic it's just a new way to say ...."


I write similar rants. My pet peeve is using "persist" to describe writing XML to a disk file; and to read it back, "depersist"... Really? It's like saying "cray-cray" instead of crazy. Do you think it makes you sound creative? Or just arrogant and a little dumb.


Hi jen !
My understanding of syntactic sugar is that such constructs make the language less homogenous and may make it look easier for beginners but conversely don't help them understand or master the primitives in the language.

The wikipedia article is really well written, you should take a look, and yes, ++/+= are syntactic sugar.


When used, the term Syntax Sugar means that you should probably look it up, and see how this thing can be desugared to better understand the topic.

I'm giving you an example:

if (true) {
  let be = 'nice!'

is desugared to:

if (true) (() => {
  var be = 'nice!'

You're welcome!


I’ve never thought about the fact that it could be misunderstood.

By the then again, I learned to ignore buzz a long time ago. It’s usually accompanied by a stinger or something that sat on a turd a moment ago.


Honestly I've only come across it once reading the MDN doc page on JS classes. I understood classes, when they first released for JS, to do nothing really different from objects. Well they allow constructors and stuff, but it was never on par with how they behave in other languages. So yeah, not a fan of classes in JS, and I saw the term as a demeaning way to refer to the feature. Marek really nailed it, but I don't see it that often.

If this is bothering you, maybe you're reading too much? That can be a problem for audodidactic learning. Sometimes you can be on the 'learn' path too much. Try making stuff rather than reading what people talk about.

As far as it being a canonical term, I don't really think it's one to bother yourself over. I've been starting a personal list of terms that I find much more valuable than syntactical sugar.


ps: imo actually using the term 'syntactical sugar' is as dull as saying any particular piece of software works by magic, or even appears to work by magic. So you have my vote for 'please stop saying syntactical sugar'. It's like 'plox', I'll never say it! It's 'plz' and only 'plz'!


I'm fine with syntactic sugar.


I hear ya, but I still think it's a useful term. For example, I much prefer the flavor and amount of sugar in C# over bitter Java. :)


I think that the best example is the JS6 Class feature.

As for the term "syntatic sugar" I think it is simple to understand so Ill keep it around.


I first heard the term when Rails first started gaining popularity and I was exposed to Ruby. I don't take it as something negative, to me it just means a language syntax feature that simplifies, it's not a different feature, just a different syntax. Like the "5.times do" syntax in Ruby, it can be done with a for or while loop just like in other languages.


I think 'syntactic sugar' is indeed a useful term (IMO) for a commonly used technique or pattern in software development.

You could say 'syntactic sugar' means putting a "sweet" or easy-to-use layer on top of a complicated piece of 'machinery'. Sort of "sugarcoating" that piece of complexity.

It's called 'sugar' because it's not changing the essence of the 'dish' (the underlying machinery is still there) but only making it taste 'sweeter'.

Async/await is a good example, if you take it away then you get to see all of the 'ugly' (well not really) promise stuff, using async/await hides that away from view but underneath it's still there.


Unnecessary features that improve the QOL of the programmer.
In Qt there is the keyword "emit" that compiles to nothing. It is only used to show the intent of the code to follow. Easing understanding later. Someone also mentioned +=, *=, -=, etc.
My gut reaction is something that may cause you to say "SWEET!", but a lot of things fall under that category.

However, QOL could encompass the entire language if the definition is taken too far. Maybe someone could define a mathematical test of syntactic sugar?


A good example of syntactic sugar is the class keyword in JavaScript. It is syntactic sugar for a constructor function. And usually, when saying syntactic sugar, there is the negative connotation of "it's not really necessary" added to it. So, those who like the class syntax don't use the term syntactic sugar for the class keyword and those who don't like it do.



Am I the only one questioning whether or not they've been living under a rock... because before coming across this article, I had NEVER heard anyone use the term "Syntactic Sugar before?


Let's call it syntactic JUICE



And then we can have SYNTACTIC SOURS!


i’ve heard this term too, and find it annoying... and i’ve been in i.t for awhile. unfortunately, some nerd thought it was cute, and it caught on. Let’s hope it goes away soon :-)

Code of Conduct Report abuse