In JavaScript, an arrow function is a shorter syntax for writing a function expression. It is also known as a "fat arrow" function because of the use of the "fat arrow" (=>) symbol.
Here is an example of a function expression written with the traditional function syntax:
function add(x, y) {
return x + y;
}
The same function can be written as an arrow function like this:
const add = (x, y) => {
return x + y;
}
Arrow functions have a number of benefits compared to traditional function expressions. One of the main benefits is that they are more concise and easier to read, especially when dealing with simple functions that only have one line of code. They also do not have their own this
value, which can be useful in certain cases.
Here are a few more examples of arrow functions:
// A function that takes no arguments and returns a string
const sayHello = () => {
return 'Hello';
}
// A function that takes one argument and returns the square of that number
const square = x => {
return x * x;
}
// A function that takes two arguments and returns their sum
const add = (x, y) => {
return x + y;
}
// A function that takes an array and returns the sum of its elements
const sum = arr => {
return arr.reduce((total, current) => total + current);
}
Note that if an arrow function only has one line of code, the curly braces and the return
statement can be omitted. For example, the square
function can be written like this:
const square = x => x * x;