Arrow function is easy way to create a function in ES6, which doesn’t create its own this reference. It always pointed this context from where it is created or called.
Arrow function doesn’t create its own scope, it always depends on the scope where it is instantiated.
About Arrow Function:
- It doesn’t has its own binding to this,arguments or super and should not be used as method,
- It is not suitable for call, apply and bind method which is generally rely on establishing a scope,
- Cannot be used as Constructor,
- Cannot use Yield method within its body,
- Doesn’t have access to new.target keyword.
- It doesn’t have Prototype property.
New Operator:
Arrow function doesn’t have constructor so it is not used to instantiate with new keyword.
const test = (x,y) => x + y;
const result = new test();
Note: throws error: test is not a constructor
Cannot be used as Method:
We can use it as a method but whenever if we have dependency of this object in the method then we cannot use it.
const People = {
name: 'angularfeed',
getName: () => {
return this.name;
}
} const result = People.getName();
console.log(result); // throw undefined
The above method will return undefined because context of this is set as global from where getName method is called and the property name in global object is not available then it return undefined.
So, instead of using arrow function as a method use traditional method to access this object reference.
Prototype Property:
Arrow function doesn’t have prototype property
const Test = (x) => x;
const result = Test.prototype.name = 'angularfeed'; // undefined
It will throw undefined because the arrow function doesn’t have property called prototype.
Yield method:
Arrow function cannot be used as a generator, because yield is not supported inside the arrow function.
call, apply and bind:
The call, apply and bind is not supported in arrow function as they are used to execute within the different scopes.
Object Literals:
Must wrap object literal inside parentheses,
const Test = () => ({name: 'angularfeed'})
Syntax:
const Example = () => {} // returns undefined(() => 'Hello World')() // return Hello Worldconst list = ['India', 'USA', 'Ireland'];
list.map((item, index) => {
return `${item} has index ${index}`;
})
References: