Use Arrows functions
Use arrow functions instead of function for cleaner and concise code:
// Function expression
const multiply = (a, b) => a * b;
// Implicit return
const square = x => x * x;
Arrow functions, also known as “fat arrow” functions, are a shorthand way to declare anonymous functions in JavaScript. They were introduced in ECMAScript 6 (ES6) and are a more concise and less verbose alternative to regular function expressions.
Here’s an example of a regular function expression:
const sum = function(a, b) {
return a + b;
};
console.log(sum(1, 2)); // 3
And here’s the equivalent arrow function:
const sum = (a, b) => {
return a + b;
};
console.log(sum(1, 2)); // 3
Arrow functions have several advantages over regular function expressions:
Shorter syntax: Arrow functions are shorter and more concise, making your code easier to read and write.
Implicit return: If an arrow function only has one expression, the value of that expression is returned automatically. You can omit the return keyword and the curly braces.
const sum = (a, b) => a + b;
console.log(sum(1, 2)); // 3
Lexical this: Arrow functions have a lexical this binding, meaning that this refers to the surrounding scope and is not affected by the context in which the function is executed.
const person = {
name: ‘John Doe’,
greet: function() {
setTimeout(function() {
console.log(`Hello, my name is ${this.name}`);
}, 1000);
}
};
person.greet(); // Hello, my name is undefined
With arrow functions, this refers to the outer person object and the code works as expected:
const person = {
name: ‘John Doe’,
greet: function() {
setTimeout(() => {
console.log(`Hello, my name is ${this.name}`);
}, 1000);
}
};
person.greet(); // Hello, my name is John Doe
In conclusion, arrow functions are a powerful and convenient feature in JavaScript that allow you to write more concise, expressive, and predictable code.