Super Micro Tutorial
Learn Something In 2 Minutes or Less!
Fed 25th, 2018
JavaScript Arrow Functions
Arrow functions in JavaScript (ES6) are a funky way to create anonymous functions. They require less typing (awesome!) and fix an issue with how 'this' is bound. Let's learn!
Anonymous functions don't have names. They're either assigned to a variable or passed into another function as a parameter:
function NotAnonymous()
{
// I'm not an anonymous function - I have a name: 'NotAnonymous'
}
let func = function()
{
// I'm anonymous! I don't have a name, but I was assigned to 'func'
};
setTimeout(function()
{
// I'm also anonymous! I was passed as a parameter to 'setTimeout'
}, 1000);
To make an arrow function (also called a 'fat arrow' function) simply drop the keyword 'function' and add '=>' after the parameters:
let foo = function()
{
// Regular anonymous function
};
let bar = () =>
{
// Arrow function!
};
Easy peasy.
You can omit the parentheses if you only have a single parameter:
let parensRequired1 = () => {};
let parensRequired2 = (x, y) => {};
let noParensRequired = x => {};
You can also omit the curly braces if you only have a single line of code. The 'return' keyword and semicolon are implied in that case so you can get rid of those as well (so concise!):
let squaredValues = myArray.map(x => x*x);
The other big difference is that arrow functions bind 'this' to the scope of the caller. That means you don't have to save a reference to the caller's 'this':
class Thing
{
constructor()
{
this.x = 10;
}
nonArrow()
{
let self = this;
setTimeout(function()
{
// 'this' refers to the global object - not our 'Thing' object!
// this.x = undefined or ??
// self.x = 10
}, 1000);
}
arrow()
{
setTimeout(() =>
{
// 'this' refers to our 'Thing' object!
// this.x = 10
}, 1000);
}
}
One last thing: arrow functions don't get their own 'arguments' parameter:
let func = function()
{
console.log(arguments); // arguments passed to 'func'
};
let arrowFunc = () =>
{
console.log(arguments); // arguments passed to whoever called 'arrowFunc'
};
That's all there is to it! Hope you learned something!