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:
var func = x => x * x; // concise syntax, implied "return"
var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed
Example from MDN Article on Arrow Functions by Mozilla Contributors, licensed under CC-BY-SA 2.5.
These are equivalent:
// ES5
function calc(one, two) {
return one + two
}
// ES5
var calc2 = function(one, two) {
return one + two
}
// ES6 Arrow syntax
var arrowCalc = (one, two) => {
return one + two
}
// ES6 Short syntax Arrow - note no 'return' keyword, braces
var shortArrow = (one, two) => one + two
These are also equivalent:
var words = [
'cat',
'dog',
'elephant',
'crow'
];
var wordsLength1 = words.map(function(word) {
return word.length;
});
var wordsLength2 = words.map((word) => {
return word.length;
});
// If a single parameter is being passed in as an identifier, you can omit parentheses
// If an expression follows the arrow it will be returned - no return keyword necessary/allowed
var wordsLength3 = words.map(word => word.length);
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:
var myObject = () => ({
firstName: "John",
lastName: 'McLane'
});
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