Refactor es5 functions to es6 arrow functions

Mike Sherov
InstructorMike Sherov
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

In this lesson we'll learn how to refactor es5 functions into es6 arrow functions to decrease visual noise in our program. We'll take a step by step approach, increasing clarity with each rewrite.

Man 1: [00:00] Here we have an array of animals. Each animal is an object with properties of name and leg.

[00:09] We have filtered and mapped this array such that it returns only the names of the animals with two legs. If we run this code, we see that it outputs humans. The problem with the Array.prototype methods is that if they're used with ES5 functions, they often come out verbose.

[00:27] Let's refactor this to ES6 functions. The first thing we do is remove the function keyword and add a fat arrow between the parentheses and the curly brace. If we run this code again, we see that it still outputs humans.

[00:43] Next, if the function only has one parameter, you could remove the parentheses around that parameter and you could see it still works.

[00:52] Lastly, if your function is a single expression, that expression is a returned expression, you could remove the curly braces, remove the semicolon after the expression, remove the return keyword, and there will be an implicit return of the expression, still humans.

[01:14] As you can see, the ES6 version of this code is a lot less verbose than the ES5 version of this code. We simply want to get the names of the animals with two legs. Compare this to the ES5 version of this code, which has the function keyword, the return keyword, multiple line curly braces, and parentheses around the function parameter.