DEV Community

Cover image for Sh*tpost: can we stop saying "syntactic sugar"?
Jen Chan
Jen Chan

Posted on

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

"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 usually one to squabble over the semantic aspects of any language... but this noun has sent me into a confusing tailspin before.

The first time I heard of the term "syntactic sugar" was in relationship to React. I heard about it in terms of JSX in a Wes Bos React video. Then it was described as such in terms of async and await. Hell, there are even talks on this!

syntactic sugar toy story meme

(Without Googling) What I interpret it to mean between seasoned developers, is that syntactic sugar is an aspect of a language or framework that allows devs to write code in an abbreviated, clear and/or easier way.

For example, writing JSX helps with integrating javascript into HTML in a view while writing partials. Async/await makes Javascript look as if it's synchronous while reminding us it's going to run asynchronously, pause the execution of a function and wait til a promise resolves or information returns.

Couldn't it be argued that anything that abbreviates or makes writing code simpler and cleaner "syntactic sugar"? Wouldn't template literals, destructuring or even ++ and += then be syntactic sugar?

Despite the analogy, the term "syntactic sugar" did not/is not helping me, or learners understand what the very sweet, refined characteristic of a language or framework does!

Every time I hear it, I'm just going to omit and continue reading the examples.

rant.end()

Ok. I'm open to hearing how this term is canonical and useful. It's likely I'm just "young" on my second career and disgruntled.


So I did have to google if anyone on the internet shared my opinion, and this post seems to place my sentiments more eloquently.

I needed a definition anyway, so here are some resources I found helpful:
Sweet API – Syntactic Sugar And You
Quora | What is Syntactic Sugar?

Top comments (56)

Collapse
 
marek profile image
Marek Zaluski • Edited

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.

Collapse
 
togakangaroo profile image
George Mauer

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.

Collapse
 
sudojoe profile image
Joseph Locke • Edited

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.

Consider:

const doSomething = () => {
  somethingElse().then(() => anotherThing());
};
Enter fullscreen mode Exit fullscreen mode

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();
  anotherThing();
};
Enter fullscreen mode Exit fullscreen mode

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().

Collapse
 
jenc profile image
Jen Chan • Edited

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.

Collapse
 
nestedsoftware profile image
Nested Software

@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.

Thread Thread
 
jenc profile image
Jen Chan

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

Collapse
 
andreirusu_ profile image
Andrei Rusu

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.

Collapse
 
moopet profile image
Ben Sinclair

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.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

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.

Collapse
 
jenc profile image
Jen Chan • Edited

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?!"

Collapse
 
codemouse92 profile image
Jason C. McDonald

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.

Thread Thread
 
mycarrysun profile image
Mike Harrison

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!

Collapse
 
codemouse92 profile image
Jason C. McDonald

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!

Collapse
 
jenc profile image
Jen Chan

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).

Thread Thread
 
drbearhands profile image
DrBearhands

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

Collapse
 
antonioplacerda profile image
Antonio P Lacerda

This reply is great on so many levels!

Collapse
 
jenc profile image
Jen Chan

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

Collapse
 
antonfrattaroli profile image
Anton Frattaroli

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
{
    get
    {
        return propertyField;
    }

    set
    {
        propertyField = value;
    }
}
Collapse
 
jenc profile image
Jen Chan

Well I guess coffeescript is complete syntax caramel then!

That is a really clear example, thanks!

Collapse
 
eljayadobe profile image
Eljay-Adobe

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!

Thread Thread
 
antonfrattaroli profile image
Anton Frattaroli

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

Collapse
 
timellison profile image
Tim Ellison

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.

Collapse
 
lysofdev profile image
Esteban Hernández

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 )

Collapse
 
jckuhl profile image
Jonathan Kuhl

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.

Example:

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.

(stackoverflow.com/questions/200014...)

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.

Collapse
 
jenc profile image
Jen Chan

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.

Collapse
 
jenc profile image
Jen Chan

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

Collapse
 
ver_kat profile image
Veronika T

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.

Collapse
 
jenc profile image
Jen Chan

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".

Collapse
 
ver_kat profile image
Veronika T

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.

Collapse
 
gabek profile image
Gabe Kangas

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.

Collapse
 
jenc profile image
Jen Chan

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.

Collapse
 
cjbrooks12 profile image
Casey Brooks • Edited

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.

Collapse
 
anwar_nairi profile image
Anwar

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!

Collapse
 
andreirusu_ profile image
Andrei Rusu

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.

Collapse
 
ryansmith profile image
Ryan Smith • Edited

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.