Javascript Arrow function
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
The syntax for arrow function:
(param1, param2) => expression
Basic Example:
const sum = (a, b) => a + b
Following are some syntactical rules for the arrow function
- We don’t need to use parentheses if the function has only one parameter and single-line function body doesn’t need brackets and return keyword.
- If function having more than one parameters or with no parameter then we must have to use parentheses.
- Multi-line statements require brackets and return keyword.
- parentheses are required around expression while returning an object literal expression.
param => ({key: val})
- Default parameters are supported
(name=admin, age=21, address) => expression
'this' in arrow function
The arrow function does not have its own this.
window.a = 1; function Demonstration(){ this.a = 10; setTimeout(() => { console.log(this.a); },1000); } var d = new Demonstration();
Arrow functions follow the normal variable lookup rules. So while searching for this which is not present in the current scope, an arrow function ends up finding the this from its enclosing scope.
Important things to remember
- The call, apply and bind methods are NOT suitable for Arrow functions. As they were designed to allow methods to execute within different scopes because Arrow functions establish "this" based on the scope the Arrow function is defined within.
- this refers to the instance. Instances are created when the new keyword is invoked. Otherwise, this will default to the window scope.
- The greatest benefit of using Arrow functions is with DOM-level methods (setTimeout, setInterval, addEventListener) that usually require some kind of closure, call, apply or bind to ensure the function executed in the proper scope.
- Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope
- In most cases, using rest parameters is a good alternative to using an arguments object.
- The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, Arrow functions cannot be used as generators.
Differences & Limitations
- Does not have its own bindings to this or super, and should not be used as methods.
- Does not have arguments, or new.target keywords.
- Not suitable for call, apply and bind methods, which generally rely on establishing a scope.
- Can not be used as constructors.
- Can not use yield, within its body.
Front End Developer | 6 Years Experience | Specialist in JavaScript Frameworks
4 å¹´Nice Article Shubham ??