🧁Arrow Functions
In JavaScript, an arrow function (also known as a "fat arrow function") is a shorthand way to define a function. Arrow functions have a shorter syntax compared to regular functions and also have a lexical this
binding.
The basic syntax of an arrow function is as follows:
or
Here's an example of an arrow function that takes two parameters, x
and y
, and returns their sum:
If the arrow function only has one parameter, the parentheses can be omitted:
If the arrow function only has one statement, the curly braces and the return
keyword can be omitted:
Arrow functions also have a lexical this
binding, which means that the this
keyword inside an arrow function refers to the this
of the surrounding scope, rather than the object on which the function is called. This can be useful in situations where the this
keyword would normally be unpredictable. For example, when you use a function as a callback, the this
keyword inside that function might not be what you expect.
Here's an example of an arrow function being used as a callback:
Arrow functions have a shorter syntax, making them easier to read, and have a lexical this
binding, which makes them useful in situations where the this
keyword would normally be unpredictable, such as when using functions as callbacks. However, they cannot be used as constructors and don't have a prototype property.
Last updated