Ben Garrison


Javascript ES6 — Arrow Functions and Lexical `this`

August 19th 2017

One of the most anticipated new features in the ES6 Javascript standard was the Arrow Function Expression. It promises a shorter syntax than it’s predecessor the Function Expression. In addition(and IMHO more exciting) is how the new Arrow Function binds, or actually DOES NOT bind it’s own this. Arrow Functions lexically bind their context so this actually refers to the originating context.

Let’s take a deeper look at both of these implementations.

Keep in mind that ES5 references below generically mean pre-ES6.

A lot of people have been asking about the editor theme in use in these tutorials. It’s the AYU Sublime theme coupled with the Apple SF font(thin).

If you like this post check, out my recent post on Component sharing via react-native-web and give me a follow on twitter:

Basic Arrow Function Syntax

We will get to some more concrete examples in a second, but let’s get this out of the way first.

basic arrow fn syntax

You can see the basic syntax for a statement on line 3 and an expression on line 4. Note the line 4 equivalent on line 5. With single parameter functions, parentheses are optional(lines 8–9). No param function example on line 12.

Shorter Functions

Example 1

shorter functions ex 1

Note the ES5 .map() function on line 12. An ES6 implementation on line 17 and a BETTER ES6 implementation on line 22.

Example 2(Expressions and Statements)

shorter functions ex 2

Lexical this

Se we have established that the syntax for ES6 Arrow Functions is superior to previous standards, now let’s take a look at the execution context implications.

In the past you may have chosen the common pattern of a top-level thisfollowed by a nested web of .bind(this)and self=thisstatements. Check out this representation below.

lexical this

Lines 4, 11 and 17 all offer ES5 implementations for managing existing execution context limitations. You can see on Line 24 the ES6 Arrow Function lexical this context.

So HOW exactly is ‘lexical this’ allowing us to pass execution context? By using ‘lexical scoping’. Lexical Scoping just means that it uses thisfrom the code that contains the Arrow Function.

I think a good way to finish this article would be to sum up the overall state of functions in ES6. You will likely hardly ever see old school functions as ES6 begins to take hold:

  • Constructor functions will hopefully be replaced by class declarations
  • Functions as subroutines will be replaced by arrow functions
  • Functions as methods will be replaced by method definitions

So that’s it for Arrow Functions in ES6. Let me know your thoughts and questions and give me a follow on twitter. Keep after it.

If you like this article, please recommend and share to help others find it!

More by Ben Garrison

More Related Stories