Arrow Functions in ECMAScript 6
ES6, JavaScript
ES6 introduces a new syntax for writing JavaScript functions: arrow functions. Arrow function expressions have more concise syntax than a function expression.
Arrow functions also allow you to access this
from a surrounding method.
Arrow functions can have either a “concise body” or a “block body” form:
Example from MDN Article on Arrow Functions by Mozilla Contributors, licensed under CC-BY-SA 2.5.
These are equivalent:
These are also equivalent:
Example adapted from MDN Article on Arrow Functions by Mozilla Contributors, licensed under CC-BY-SA 2.5.
Implicit Return
Implicit return only happens for single statement arrow functions. If an arrow function is declared with {}, even if it’s a single statement, implicit return does not occur.
Returning Object Literals
Wrap the object literal in parentheses - code inside {}
is parsed as a sequence of statements.
Function that returns an object:
Line Breaks
Line breaks between parameters and the arrow are not allowed.
References
- MDN Article on Arrow Functions - good reference article
- Good description of Arrow Funcions - outlines lexical variables in arrow functions
comments powered by Disqus