Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Refactor es5 functions to es6 arrow functions

    Mike SherovMike Sherov
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss