Skip to main content

JavaScript Arrow Functions

JavaScript arrow functions are one of those bits of syntax about which I occasionally have a brain freeze. Here’s a quick refresher for those moments.

Differences between arrow functions and traditional functions

Arrow functions are shorter than traditional function syntax.

They don’t bind their own this value. Instead, the this value of the scope in which the function was defined is accessible. That makes them poor candidates for methods since this won’t be a reference to the object the method is defined on. However it makes them good candidates for everything else, including use within methods, where—unlike standard functions—they can refer to (for example) this.name just like their parent method because the arrow function has no overriding this binding of its own.

TL;DR: typical usage

const doStuff = (foo) => {
// stuff that spans multiple lines
};

// short functions
const add = (num1, num2) => num1 + num2;

Explainer

// Traditional Function
function (a) {
return a + 100;
}

// Arrow Function Breakdown

// 1. Remove "function", place => between argument and opening curly
(a) => {
return a + 100;
}

// 2. Remove braces and word "return". The return is implied.
(a) => a + 100;

// 3. Remove the argument parentheses
a => a + 100;

References

External Link Bookmark Note Entry Search