Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

Can you offer a use case for the new arrow => function syntax?

How does this new syntax differ from other functions?
Topics
JAVASCRIPT
Edit on GitHub

TL;DR

Arrow functions provide a concise syntax for writing functions in JavaScript. They are particularly useful for maintaining the this context within methods and callbacks. For example, in an event handler or array method like map, arrow functions can simplify the code and avoid issues with this binding.

const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6]

Use case for the new arrow => function syntax

Simplifying syntax

Arrow functions provide a more concise way to write functions. This is especially useful for short functions or callbacks.

// Traditional function
const add = function (a, b) {
return a + b;
};
// Arrow function
const add = (a, b) => a + b;

Lexical this binding

Arrow functions do not have their own this context. Instead, they inherit this from the surrounding scope. This is particularly useful in methods and callbacks where the this context can be tricky.

function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
const timer = new Timer();

In the example above, using a traditional function inside setInterval would require additional steps to maintain the correct this context.

Using arrow functions in array methods

Arrow functions are often used in array methods like map, filter, and reduce for cleaner and more readable code.

const numbers = [1, 2, 3, 4, 5];
// Traditional function
const doubled = numbers.map(function (n) {
return n * 2;
});
// Arrow function
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

Event handlers

Arrow functions can be used in event handlers to maintain the this context of the class or object.

class Button {
constructor() {
this.count = 0;
this.button = document.createElement('button');
this.button.innerText = 'Click me';
this.button.addEventListener('click', () => {
this.count++;
console.log(this.count);
});
document.body.appendChild(this.button);
}
}
const button = new Button();

Further reading

Edit on GitHub