Why You Need Arrow Function in JavaScript?

Introduction

Arrow functions are a new syntax introduced in ES6 and are now widely used. Reading this article will help you understand arrow functions and their features, as well as considerations to keep in mind.

Syntax

To use arrow functions, as the name suggests, you will use the arrow-like symbol => to define a function. Here are some syntax examples of arrow functions:

// Regular function
function functionName(parameter) {
// ...
}
// No parameters
const functionName = () => {
// ...
};
// One parameter (parentheses can be omitted)
const functionOne = parameter => {
// ...
};
// Multiple parameters (parentheses are required)
const functionTwo = (parameter, parameterTwo) => {
// ...
};
// Destructured parameters (parentheses are required)
const functionTwo = ({parameter}) => {
// ...
};
// Default parameters (parentheses are required)
const functionTwo = (parameter = {}) => {
// ...
};

functionName is the name of the function, and parameter is the function’s parameter, which can have multiple parameters. If there are no parameters, use empty parentheses () instead.

Features

Arrow functions have some interesting features to note.

Implicit Return

Regular functions require a return value using the return keyword. If there is no return value, undefined is returned. Arrow functions have a feature that allows for implicit return, meaning you do not need to use the return keyword to return a value. Refer to the following examples:

// Single line
const implicit = (value) => value;
// Multi-line (enclosed in parentheses)
const implicit = (value) => (
value
);
// Incorrect usage (objects must be enclosed in parentheses to avoid being misinterpreted as the start of a function)
const implicit = () => {
value: 'Hello';
};
implicit(); // undefined
// Correct way to return an object
const implicit = () => ({ value: 'Hello' });
implicit(); // { value: "Hello" }

No arguments

Arrow functions do not have an arguments parameter because they inherit the arguments object from their parent scope. This means that when referencing arguments within an arrow function, you are actually referencing the arguments from its parent scope. We can use the following method to obtain all parameters passed to the anonymous function.

const myFunction = (...args) => {
console.log(args);
};
myFunction(1, 2, 3); // Outputs [1, 2, 3]
### `this` Does Not Exist
Arrow functions do not have `this`, so if you access `this`, it will inherit `this` from the outer scope.
```javascript
const bar = 'global apple';
const foo = {
bar: 'local orange',
normalFunction: function () {
// Traditional function creates a scope based on this
console.log('1', this.bar); // 1 global apple
setTimeout(() => {
console.log('2', this.name); // 2 local orange
console.log('3', this); // 3 foo
}, 1000);
},
arrowFunction: () => {
// If using an arrow function, this points to the outer scope
console.log('4', this.name); // 4 global apple
setTimeout(() => {
console.log('5', this.name); // 5 global apple
console.log('6', this); // 6 window
}, 1000);
},
};
foo.normalFunction();
foo.arrowFunction();
```

Practical Uses

Case 1: Simplifying Code

The most common way to use arrow functions is to make the code more concise, but it is important to note that concise code does not always mean better readability. In appropriate situations, using arrow functions to simplify code is feasible, and there is no hard rule; it depends on personal preference.

// Example of a regular function:
function add(a, b) {
return a + b;
}
// Using an arrow function to simplify the code:
const add = (a, b) => a + b;
// Example of a regular function:
document.getElementById('increment').addEventListener('click', function () {
count++;
});
// Using an arrow function to simplify the code:
document.getElementById('increment').addEventListener('click', () => {
count++;
});
// Convert each element in an array to li tags
// Result: [ "<li>John</li>", "<li>Mary</li>", "<li>Peter</li>" ]
const persons = ['John', 'Mary', 'Peter'];
persons.map((person) => `<li>${person}</li>`);

Case 2: Letting this Point to the Outer Scope

Just like the previous example of global apple and local orange, appropriately using arrow functions can allow this to point to the outer scope, achieving specific purposes.

Summary

Utilizing arrow functions not only makes the code more concise but also possesses some unique properties worth exploring!