In JavaScript, an arrow function is a shorter syntax for writing a function expression. It is similar to the traditional function syntax, but it does not have it's own `this`, `arguments`, `super`, or `new.target` values. Instead, these values are inherited from the surrounding context. Here is an example of an arrow function that takes a single argument `x` and returns the value of `x` multiplied by `2`:
const double = (x) => {
return x * 2;
};
console.log(double(4)); // Output: 8
You can also use the concise syntax if the function body consists of a single statement that returns a value:
const double = x => x * 2;
console.log(double(4)); // Output: 8
Arrow functions are often used in modern JavaScript code because they are more concise and easier to read than traditional function expressions. They are especially useful when working with higher-order functions, such as `map`, `filter`, and `reduce`.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(x => x * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Comments (0)