Arrow Function Notes After Watching ES6 For Everyone

Note post: this short post about Arrow Functions after watching ES6 For Everyone(EFE——for this post) by Wes Bos! Arrow functions are simpler way to write functions in JavaScript. This post contains a few things that I wasn't completely clear on about Arrow Functions that EFE really clarified for me.

Arrow Function Illuminations:

  1. This will be undefined.
  2. Your can remove even more code cruft that is usually done with Arrow Functions (no mustache brackets needed).
  3. Arguments which are objects will not work in arrow functions

Deeper Dive

When writing a function normal this can be bound to things (like elements in example). With arrow functions, this (pun intended) is not the case.

The This Key Word Is Undefined

ES5 Function

var clickFunction = function clickFunc() {
  // This would be the selected element
var button1 = document.getElementById('button-1');
button1.addEventListener('click', clickFunction, false);

ES6 Arrow Function

document.getElementById('elem').addEventListener('click', () => {
  // `this` would be undefined

Remove Even More Cruft With Arrow Functions

Arrow functions can be even more minimal but most people add certain things like mustaches for legibility.

Standard Way of Writing an Arrow Function

const button2 = document.getElementById('button-2');
button2.addEventListener('click', () => {
  console.log('Normal arrow function');

More Minimal Way An Arrow Function Can Be Written

const button3 = document.getElementById('button-3');
button3.addEventListener('click', () => console.log('arrow function with less cruft'));

Objects Cannot Be Used In Arrow Function Arguments

Arrow functions can use arguments——as long as they're not objects.

Standard Way of Writing an Arrow Function

const button4 = document.getElementById('button-4');
const anObj = {
  name: 'Objecto'
button4.addEventListener('click', (anObj) => {
  // anObj will be undefined

Arrow Function Notes Conclusion

Play with the examples above on CodePen.

What the this key word will be bound to and how minimal arrow functions can be is well documented. ES6 For Everyone gives clear examples of that make it much clearer though.

Thank you Wes Bos!!!

Update: After talking with Dan Benson a bit, I discovered even more about arrow functions. These things were covered in Wes Bos's course but I'm even clearer now. See more examples here.