# 🍬Syntactic sugar, diabetes alert🚨

Source: https://tpiros.dev/blog/syntactic-sugar-diabetes-alert

_Let's find out how to keep your sugar balanced, shall we?_

## Syntactic sugar? No, it's syntactic SUGAR!

Quick definition check:

> Syntactic sugar is a syntax aimed to express the same code command in different and mostly better ways, in the same language.

For example:

- a `Array.prototype.filter` is an alternative to  `forEach` loop for filtering out an array according to a specific condition, and
- `i++` instead of `i = i + 1`
- Or `for` is an alternative to `while` for the same purpose.

![for loop is just syntactic sugar for while loop](https://res.cloudinary.com/mayashavin/image/upload/w_400,c_fill/v1556808038/Syntactic_Sugar/5yj9h9dpghr11.png)
_So is it JUST syntactic sugar_? No. Syntactic sugar is more like **\*A\*\***lternative\***\*G\*\***ood\* syntax that's meant to empower your code with **\*S\*\***implicity\*, **\*U\*\***sability,\* and make your code more **\*R\*\***eadable\*.

I like to remember it as the **SUGAR** rule.
![](https://res.cloudinary.com/mayashavin/image/upload/v1559285452/Syntactic_Sugar/sugar_1.png)

## Keep the SUGAR on because...

### KISS works well with SUGAR

Look at this code:

```javascript
//Before syntactic sugar
const result = [];

for (let i = 0; i < data.length; i++) {
  const x = data[i];

  if (x % 2 === 0) {
    result.push(x);
  }
}
```

Swap in the syntactic sugar `filter`, refactor properly, and you get this:

```javascript
//After
const isEven = (number) => number % 2 === 0;
const result = data.filter(isEven);
```

_Shorter, more concise and easier to read._

### When SUGAR's in good use, it's extremely sweet and harmless

If you wield syntactic sugar correctly, you can dodge silly but annoying JavaScript traps. _Take the Deadpool BaNaNa trap, caused by typing too many _`+`_ to compute strings from other strings and variables:_
![Deadpool banana JS trap](https://res.cloudinary.com/mayashavin/image/upload/w_400,c_fill/v1559453409/Syntactic_Sugar/Screen_Shot_2019-06-02_at_8.29.51.png)
With the magic of string template:

```javascript
const banana = `ba${fillme}a`;
```

_Usability at its best._

### SUGAR isn't only about less code, it's also about efficiency

Think code writing efficiency, and relative performance. We all know `[[]](https://medium.com/front-end-weekly/es6-set-vs-array-what-and-when-efc055655e1a)`[ is a **better** performance choice compared to ](https://medium.com/front-end-weekly/es6-set-vs-array-what-and-when-efc055655e1a)`[new Array()](https://medium.com/front-end-weekly/es6-set-vs-array-what-and-when-efc055655e1a)`. Similarly [with ](https://medium.com/front-end-weekly/es6-map-vs-object-what-and-when-b80621932373)`[{}](https://medium.com/front-end-weekly/es6-map-vs-object-what-and-when-b80621932373)`[ instead of  ](https://medium.com/front-end-weekly/es6-map-vs-object-what-and-when-b80621932373)`[new Object()](https://medium.com/front-end-weekly/es6-map-vs-object-what-and-when-b80621932373)`[ or even ](https://medium.com/front-end-weekly/es6-map-vs-object-what-and-when-b80621932373)`[Object.create()](https://medium.com/front-end-weekly/es6-map-vs-object-what-and-when-b80621932373)`.

But **note** that performance efficiency \*really**\*differs\*\***per use case\*\*.

_And that's when SUGAR flashes the warning sign._

## Beware of JavaScript Diabetes

Everything has a limit before it becomes unbearable. Too much salt costs you your blood pressure. Too much protein causes indigestion. You need them, but in the right amount.

Same goes for syntactic sugar. It's sweet, easy to reach for, so we developers grab it whenever we can (_who wouldn't love the easy path?_). Sometimes without considering the negative effects. Because as long as it fits KISS, it's good.

_Is it? Absolutely not._

### Less code !== More readability

Look at this:
![](https://res.cloudinary.com/mayashavin/image/upload/v1559825135/Syntactic_Sugar/doSomething_1.png)
Only 2 to 3 lines of code. Concise and short.

But can you tell straight away what this block does? If you're familiar with the problem it's solving, sure. Not too hard.

(_It's for flattening an array, in case you're curious._)

**But for a first timer, it's a wall.**

_Readable? Not really._

`...` operator is another example.
![](https://res.cloudinary.com/mayashavin/image/upload/v1559825135/Syntactic_Sugar/emitEvent.png)
Lovely, but also hard to interpret. The fact that it _can be the \***\*spread\*\*** operator or the \***\*rest\*\*** parameter_ confuses many developers, especially when both appear in the same context as above.

*Your code needs to be \***\*clear\*\*** and direct before everything else, for the sake of the next developer. *Without **readability**, your beloved syntax **is no longer syntactic SUGAR.**

### Concise code !== Better performance

Less code means a lighter JS file, yes. But it doesn't necessarily make the performance better:
![](https://res.cloudinary.com/mayashavin/image/upload/v1559825534/Syntactic_Sugar/combinations_1.png)
This function, theoretically (without considering the inner loop `combinations.map()`) takes **O(n)**. Linear time. Should be good, right? But that's just theory.

_Why_? Because:

1. `map`**_loops_** through the original array, **\*creates\*\*\***new** array based on it and \***returns**\* the new array. New resource allocated. Same goes for `filter`, `reverse`, etc.
2. `reduce` also needs to **loop** through the new array _again_, and **_returns a reduced value_** based on that array with a calculation formula passed.
3. Each of these calls runs much **slower** than the original `for` loop, regardless how optimised the JS profiler is.
4. JavaScript is **single-threaded**. While it's in a loop, the browser technically _pauses_ and *waits for the iteration *to complete before moving on. The **bigger** the array, the **more logic** to execute, **_the longer the wait_**. Users start seeing the browser "freeze". Linear time doesn't really apply here.
5. **Chaining** calls like `map` and `reduce` makes things worse, not better (_the browser \***\*needs\*\*** to "freeze" for _`*map*`_ to complete, then \***\*again\*\*** for _`*reduce*`_, and so on_).
6. `for` loops don't need syntactic sugar that badly. You can rewrite the above code using `for` and still maintain KISS **with** efficiency (both in resource allocation and performance).

![](https://res.cloudinary.com/mayashavin/image/upload/v1559825419/Syntactic_Sugar/refactorCombinations_1.png)
[The syntactic version runs way slower than the classic ](http://bit.ly/map-reduce-for-benchmark)`[for](http://bit.ly/map-reduce-for-benchmark)`[ in a performance test](http://bit.ly/map-reduce-for-benchmark), despite the same time efficiency (**O(n²)**).

_It's O(n) but NOT always O(n). Be careful. Sometimes the classic _`for`_ loop wins. Period._

### Browser.support(syntactic sugar)?

Not all syntactic sugar is supported in every browser. That's why we need Babel (for instance) to make it work.
![](https://res.cloudinary.com/mayashavin/image/upload/w_500,c_fill/v1556813306/Syntactic_Sugar/2019-04-29_16-53-38.png)
Remember our little friend IE (or even Safari 9+?). Some ES6 syntactic sugar like `...` and `for..of` won't be supported, and suddenly your sweet, clean code which originally looked like this:

```javascript
const sumUp = (...numbers) => {
  let sum = 0;
  for (const number of numbers) {
    sum += number;
  }
  return sum;
};
```

After going through Babel's compiler, becomes (sort of):

```javascript
var sumUp = function sumUp() {
  for (
    var _len = arguments.length, numbers = Array(_len), _key = 0;
    _key < _len;
    _key++
  ) {
    numbers[_key] = arguments[_key];
  }
  var sum = 0;
  for (
    var _iterator = numbers,
      _isArray = Array.isArray(_iterator),
      _i = 0,
      _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();
    ;

  ) {
    var _ref;
    if (_isArray) {
      if (_i >= _iterator.length) break;
      _ref = _iterator[_i++];
    } else {
      _i = _iterator.next();
      if (_i.done) break;
      _ref = _i.value;
    }
    var number = _ref;
    sum += number;
  }
  return sum;
};
```

Suddenly **not** that efficient anymore.

_As long as your users still run certain browsers, your code needs to work on them. Before dropping a new syntactic sugar into your code, \***\*read the documentation first\*\***._

*Being extra careful with new syntax is always a good habit.*

## Conclusion

Syntactic SUGAR is good (_and totally recommended_) to use, as long as it travels with CARE:

- **C** stands for **_Check_** your use case, the syntax pitfalls, and make sure your new code meshes well with your existing logic.
- **A** stands for **_Ask for review_** (code review, architecture review, etc). The best person to ask for a code review, _to my opinion_, is a junior developer or someone new to the team. An expert eye is great, but a junior or new team member brings a fresh look and can tell you straight away whether your code is easy to follow. An extra pair of eyes never hurts.
- **R** stands for **_Read_** the documentation, read others' code and remarks. Make your code readable by providing a README file or explanation comments. _But only when needed, because..._
- **E** stands for **_Explicit_**. Your code **should stand on its own.** Split the logic into smaller parts if it helps others understand. Good code means fewer (or no) comments. _Why would you need comments if your code is readable and explicit enough?_

Code responsibly. Think about efficiency, maintainability, readability for other developers. As long as you know your sugar limit, your syntactic sugar will stay sweet and there won't be any risk of diabetes.

**Disclaimer**: _This article is based on _[_my talk on the same subject_](https://slides.com/mayashavin/syntactic-sugar-diabetes-alert/fullscreen)_ in _[_CityJS Conf 2019 last May_](https://cityjsconf.org/speakers)_. _[_A recorded version is available on Youtube_](https://www.youtube.com/watch?v=17XXubHZ7n4&list=PL8xuokhAnn4pv5CimOe9DnAGRosVkTF4r&index=4)_. Enjoy and happy coding everyone!_

_If you'd like to catch up with me sometimes, follow me on _[_Twitter_](https://twitter.com/MayaShavin)_ | _[_Facebook_](https://www.facebook.com/mayashavin/)_ or simply visit my _[_portfolio website_](https://mayashavin.com)_._
