ES6 Syntactic Sugar and Practical Uses

Nick Fewings via Unsplash

Introduction

With the release of JavaScript ES6 came the introduction of arrow functions. Arrow functions are a concise, syntactically sweet variation on the traditional function expression. While it has its pros, it also has some cons. Let’s take a look!

Overview

A traditional function expression looks something like this:

Console of Function Expression

The snazzy arrow function would look like this:

Console of Arrow Function

Notice how this can be nicely compacted into a one line statement. Pretty cool, huh?

Syntax and Guidelines

If you’re already hip with arrow functions, you might have noticed that the above example is actually an abbreviated version of an arrow function. A more typical arrow function would look like this:

addNumsArrow = (num1, num2) => {
return num1 + num2
}

If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword — like in the earlier example. Other guidelines are as follows:

// No arguments === blank parenthesis 
sayHi = () => {
return 'Hello World'
}
// One argument === parenthesis optional
sayHiName = name => {
return `Hi, ${name}`
}
// or
sayHiName = (name) => {
return `Hi, ${name}`
}
// Multiple arguments === parenthesis required
sayHiWithDay = (name, day) => {
return `Hi, ${name}. Happy ${day}!`
}
// NOTE: all of the above could be implemented as one liners.// If the function has multiple lines of code, curly brackets and a return statement are required
sayHiName = (name) => {
if(!name){
return 'Hi! Nice to meet you!'
} else
return `Hi, ${name}. Nice to meet you!`
}

This and Scoping

The handling of thisin arrow functions is slightly different. As per the MDN documentation:

The call, apply and bind methods are NOT suitable for Arrow functions -- as they were designed to allow methods to execute within different scopes -- because Arrow functions establish "this" based on the scope the Arrow function is defined within.

Because of this, arrow functions have a benefit. Again, from MDN:

Perhaps the greatest benefit of using Arrow functions is with DOM-level methods (setTimeout, setInterval, addEventListener) that usually require some kind of closure, call, apply or bind to ensure the function executed in the proper scope.

Conclusion

Arrow functions are a great tool for helping keep code neat and concise. The main difference between regular function expressions and arrow functions is in how it defines this and handles scope. Arrow functions also do not contain “class like” properties(ie. can’t be used as constructors and don’t have a property object). Because of this, be aware of how, when, and where functions are used and called to determine whether or not an arrow function is appropriate. Reference MDN for learning more on arrow functions, function expression, and scope. Thanks for reading, and happy coding!