Arrow Function Quirks

  • Below are equivalent
    • var smartPhones = [
      { name:’iphone’, price:649 },
      { name:’Galaxy S6′, price:576 },
      { name:’Galaxy Note 5′, price:489 }
      var a = function(y) {
      } // is same as =>a(r))
  • an arrow function with a block body does not automatically return a value. Use a return statement for that.
  • Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
    • Use non-arrow functions for methods that will be called using the object.method() syntax. Those are the functions that will receive a meaningful this value from their caller.
    • Use arrow functions for everything else.
  • arrow functions are anonymous, which means that you won’t have a self-bound lexical identifier to self-reference, for recursion, event handler unbinding, etc. Yes, ES6 has “name inference”, but that only assigns an internal .name property to the function object — it provides no lexical relief.
  • wrapping object literals in parentheses is the only trick you need to remember
    • all the new ES6 parameter forms, like default values, destructuring, rest params, etc… all those force you to use ( ) around the param list, even if only using the one param.
    • There is one caveat when using arrow functions to create plain objects. Always wrap the object in parentheses:
      // create a new empty object for each puppy to play with
      var chewToys = => {});   // BUG!
      var chewToys = => ({})); // ok

      Unfortunately, an empty object {} and an empty block {} look exactly the same. The rule in ES6 is that { immediately following an arrow is always treated as the start of a block, never the start of an object. The code puppy => {} is therefore silently interpreted as an arrow function that does nothing and returns undefined.

      Even more confusing, an object literal like {key: value} looks exactly like a block containing a labeled statement—at least, that’s how it looks to your JavaScript engine. Fortunately { is the only ambiguous character, so wrapping object literals in parentheses is the only trick you need to remember.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s