Arrow functions / Fat arrow functions

  • has context of lexical bound this
  • anonymous

Syntax variations

VariationExample
No parameters() => console.log('Hi')
or
_ => console.log('Hi')
Single parameterx => x * x
Multiple parameters(x, y) => x * y
Body blockx => {
let y = x * 3;
return y;
}
Returns Object literalsx => ({y: x})

Anonymity creates some issues

  • Hard to debug
  • No self-referencing (eg. recursion, event handler that needs to unbind)

When not to use

  • Object methods

    • this is not bound to anything, and will inherit the value of this from its parent scope
    var obj = {
    a: 1,
    get: () => {
    return this.a;
    }
    };

    console.log(obj.get()); //undefined
  • Callback functions with dynamic context

    var button = document.getElementById('press');

    button.addEventListener('click', () => {
    this.classList.toggle('on'); //TypeError
    });

When to use

  • requires this to be bound to the context, and not the function itself.

Resources