blog

  • Home
  • blog
  • ES6 Arrow Functions: Fat and Concise Syntax in JavaScript

ES6 Arrow Functions: Fat and Concise Syntax in JavaScript

Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope. Surveys show they’re the most popular ES6 feature:

Arrow functions: Axel Rauschmayer survey on favorite ES6 features

Source: Axel Rauschmayer survey on favorite ES6 features

Arrow functions: Ponyfoo’s survey on the most commonly used ES6 features

Source: Ponyfoo’s survey on the most commonly used ES6 features

The good news is that many major modern browsers support the use of arrow functions.

This post will cover the details of arrow functions — how to use them, common syntaxes, common use cases, and gotchas/pitfalls.

What Are Arrow Functions?

Arrow functions – also called “fat arrow” functions, from CoffeeScript (a transcompiled language) — are a more concise syntax for writing function expressions. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way this binds in functions.

Arrow functions make our code more concise, and simplify function scoping and the this keyword. They are one-line mini functions which work much like Lambdas in other languages like C# or Python. (See also lambdas in JavaScript). By using arrow functions, we avoid having to type the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.

Using Arrow Functions

There are a variety of syntaxes available in arrow functions, of which MDN has a thorough list. We’ll cover the common ones here to get you started. Let’s compare how ES5 code with function expressions can now be written in ES6 using arrow functions.

Basic Syntax with Multiple Parameters (from MDN)

// (param1, param2, paramN) => expression

// ES5
var multiplyES5 = function(x, y) {
  return x * y;
};

// ES6
const multiplyES6 = (x, y) => { return x * y };

Code Example at JSBin.

The arrow function example above allows a developer to accomplish the same result with fewer lines of code and approximately half the typing.

Curly brackets aren’t required if only one expression is present. The preceding example could also be written as:

const multiplyES6 = (x, y) => x * y;

Basic Syntax with One Parameter

Parentheses are optional when only one parameter is present

//ES5
var phraseSplitterEs5 = function phraseSplitter(phrase) {
  return phrase.split(' ');
};

//ES6
const phraseSplitterEs6 = phrase => phrase.split(" ");

console.log(phraseSplitterEs6("ES6 Awesomeness"));  // ["ES6", "Awesomeness"]

Code Example at JSBin.

No Parameters

Parentheses are required when no parameters are present.

//ES5
var docLogEs5 = function docLog() {
    console.log(document);
};

//ES6
var docLogEs6 = () => { console.log(document); };
docLogEs6(); // #document... <html> ….

Code Example at JSBin.

Object Literal Syntax

Arrow functions, like function expressions, can be used to return an object literal expression. The only caveat is that the body needs to be wrapped in parentheses, in order to distinguish between a block and an object (both of which use curly brackets).

//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
  return {
    id: id,
    name: name
  };
};

// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });

console.log(setNameIdsEs6 (4, "Kyle"));   // Object {id: 4, name: "Kyle"}

Code Example at JSBin.

Use Cases for Arrow Functions

Now that we’ve covered the basic syntaxes, let’s get into how arrow functions are used.

One common use case for arrow functions is array manipulation and the like. It’s common that you’ll need to map or reduce an array. Take this simple array of objects:

const smartPhones = [
  { name:'iphone', price:649 },
  { name:'Galaxy S6', price:576 },
  { name:'Galaxy Note 5', price:489 }
];

We could create an array of objects with just the names or prices by doing this in ES5:

// ES5
var prices = smartPhones.map(function(smartPhone) {
  return smartPhone.price;
});

console.log(prices); // [649, 576, 489]

An arrow function is more concise and easier to read:

// ES6
const prices = smartPhones.map(smartPhone => smartPhone.price);
console.log(prices); // [649, 576, 489]

Code Example at JSBin.

Here’s another example using the array filter method:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

// ES5
var divisibleByThrreeES5 = array.filter(function (v){
  return v % 3 === 0;
});

// ES6
const divisibleByThrreeES6 = array.filter(v => v % 3 === 0);

console.log(divisibleByThrreeES6); // [3, 6, 9, 12, 15]

Code Example at JSBin.

Continue reading %ES6 Arrow Functions: Fat and Concise Syntax in JavaScript%

LEAVE A REPLY