Notes
[ES2015] Arrow Functions
pros and cons of ES2015 arrow functions, lexical this vs anonymous stack traces, and all the syntax variations
JavaScript
2 minutes
Arrow Functions
Arrow functions are anonymous function expressions. They don’t show up in stack traces.
Pros
- Shorter syntax. You get to remove
function,returnand some{..} - Shines with
thiskeyword. The arrow function doesn’t have it’s ownthisso we automatically get a lexicalthis(bind to the outer context). Skipping.bind(this)
Cons
- Show up as anonymous in stack trace, makes debugging/troubleshooting hard. Imagine minified code, error at line 1, character 32712.. and you’ll have no idea what that is. Named functions are the way to go if you want names to show up in stack trace. Name inferencing is the closest thing you get with arrow functions, which is when you assign the anonymous function to a named variable.
- makes testing difficult because you can’t
console.logwhen using the concise arrow function syntax. You have to change the syntax first in order toconsole.log(). - Inconsistant syntax. Variations in syntax, too many ways to write an arrow function (definitely more than 6 syntactical ways)
- No self-reference (arrow functions are anonymous funcs, remember?) Without self-reference you can’t do cool things like recursion or have event handlers that needs to unbind itself once it’s run
- Not everyone knows the syntax, not very beginner friendly
Syntax Variations
1=> 3 // or (var foo = => 3) headless syntax proposal
2() => 3 // no params
3(x) => 3
4x => 3 // no parens, placeholder for params looks an awful lot like funcion invocation
5(x,y) => 3 // parens
6(...x) => 3 // parens
7
8x => { try { 3 } catch(e) {} }
9x => { return 3 }
10x => ({ y: x}) // gotta wrap parens around the object body in order to return an object
Name inferencing
1var foo = x => 3
2foo.name // "foo" the interpretor made a guess (inferred) that you want to reference the function with the name foo, based upon where the function expression got saved.
Name inferencing doesn’t work when you pass an arrow function as a param to another function. They’re gonna stay syntactically anonymous.
1foo( x => 3)
Notes
- without the
{}it’s an implied return. if you use{}you gotta use the return keyword inside as well. Or have curly brackets wrapped in parens({ .. })
