[ES2015] Arrow Functions
Arrow Functions
Arrow functions are anonymous function expressions. They don’t show up in stack traces.
Pros
- Shorter syntax. You get to remove
function
,return
and some{..}
- Shines with
this
keyword. The arrow function doesn’t have it’s ownthis
so 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.log
when 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
=> 3 // or (var foo = => 3) headless syntax proposal
() => 3 // no params
(x) => 3
x => 3 // no parens, placeholder for params looks an awful lot like funcion invocation
(x,y) => 3 // parens
(...x) => 3 // parens
x => { try { 3 } catch(e) {} }
x => { return 3 }
x => ({ y: x}) // gotta wrap parens around the object body in order to return an object
Name inferencing
var foo = x => 3
foo.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.
foo( 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({ .. })