Javascript Arrow Function
Arrow functions in JavaScript are a concise syntax for defining functions. They were introduced in ECMAScript 6 (ES6) and provide a more streamlined way to write functions compared to traditional function expressions.
Arrow functions are most famously used to preserve their lexical context of "this", as they have static binding. What this means is that, while passing arrow functions from one context to another (functions or modules), the value of "this" doesn't change.
Arrow Function Syntax
The syntax of the arrow function is:
If the body has a single statement or expression, you can write the arrow function as:
let myFunction = (arg1, arg2, ...argN) => expression
Following things we should avoid while using arrow functions:-
- We should not use arrow functions to create methods inside objects.
- We cannot use an arrow function as a constructor.
Arrow Function with no arguments
If a function doesn't take any argument, empty parentheses are used.
Input:-
Output:-
Arrow Function with single arguments
If a function has only one argument, we can omit the parentheses.
Input:-
Output:-
Multiline Arrow Function
If a function body has multiple statements, we need to put them inside curly brackets {}.
Input:-
Output:-
Arguments binding
When we pass arguments to a regular function, we can access them using the arguments keyword. Arrow functions do not have this feature of argument binding and if we try to access an argument using the arrow function, it will give an error.
Input:-
Output:-