Arrow functions
Arrow functions are a compact and shorthand syntax for writing function expressions in JavaScript that were introduced with ES6. They are anonymous and change the way `this` binds in functions.
Here is a simple example of an arrow function:
const square = (x) => {
return x * x;
};
In this example, the `square` function takes a number `x` as a parameter and returns the square of that number. The function doesn't have a name and is assigned to the variable `square`.
Arrow functions can be made even shorter with implicit return for one-line expressions.
const square = x => x * x;
The above function does exactly the same as the previous example, but it's shorter. Because there's only one argument, we can omit the parentheses `( )`, and because the function body only contains one line of code that is being returned, we can omit the `return` statement and the `{ }` as well.
Another key feature of arrow functions is that they don't have their own `this` value. `this` has the same value as in the surrounding code (lexical `this`). That makes arrow functions particularly useful when working with event listeners or callbacks within methods on an object, where you want `this` to refer to the object and not the function.
Comments
Post a Comment