DEV Community

Alex Suarez
Alex Suarez

Posted on • Edited on

Syntactic sugar, why, when and how

The term Syntactic Sugar was coined by Peter J. Landin in 1964. In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

The Why
It demonstrates the domain of native APIs, brings more flexibility and readability to the code, it can help others to find new ways to write more short and concise code, and I can go ahead all-day long.

When
Every time you have a change!

How... Let's go

 // don't
 let alex = personal.alex

 // do destructuring
 let {alex} = personal
Enter fullscreen mode Exit fullscreen mode
// don't if variable asignation may not vary
var isSuperHuman = superhuman ? "is super human" : "nahh"

// use const instead
const isSuperHuman = superhuman ? "is super human" : "nahh"
Enter fullscreen mode Exit fullscreen mode

// arrays to avoid for loops o foreach
arr.find(i => i.id === "01") // returns the object

// with destructuring
arr.find(({id}) => id === "01") // returns the object

arr.filter(({id}) => id === "01") // returns and array of matches elements

arr.some(({id}) => id === "01") // returns boolean value

arr.every(({type}) => type === "superhumen") // returns boolean value if every nodes matched the criteria

arr.reduce((acc, {age}) => acc + age, 0) // returns a reduced value in this case the sum of all ages

// concat and push are from the pass now we spread!
const a = [...arr, newElemet]

// or to place the new element at the top of the array
const a = [newElemet, ...arr]

// mergin to arrays
const a = [...arrB, ...arrC]

// or flatted!!
const a = [arrB, arrC].flat()

// get the unique values (names) from array, lets map?
const a = ...new Set(data.map(i => i.name))

// as array?
const a = [...new Set(data.map(i => i.name))]
Enter fullscreen mode Exit fullscreen mode
  • But Alex I already know that man!
// number to strings?
100.toString() // "100"

// what about!
100 + "" // "100"

// strings to number?
Number("100") // 100
parseInt("100") // 100
parseFloat("100").toFixed(2) // 100.00

// what about!
"100" * 1 // 100
Enter fullscreen mode Exit fullscreen mode
  • Of curse, I know that too!

If that is the case, my friend you may be the sweetest person in the whole world!

Just let me know how do you declare functions?


// as a declaration
function sum(a,b) {
  return a + b
}

// as expression 
const sum = function(a,b) {
  return a + b;
};

// as an arrow?
const sum = (b,c) => b + c

// as shorthand method definition?
const operation = {
  add: (a,b) => a + b
}

// or 
const operation = {
  add(a,b){return a + b}
Enter fullscreen mode Exit fullscreen mode

See ya at the next sugar! Let me know yours.

Top comments (0)