JS Interview Question/Ans Series
The interview question series continues …
6. Tell the key points of arrow function?
Ans: Arrow function is less verbose as we have to write less code.
let test = ()=> { //syntax
//statements
}
We can write IIFE with arrow function. Function will be called immediately
(() => {
//statements
})();
this here refers to global environment in arrow function. The reference of this is not the function itself but rather the window.
let test = ()=> {
console.log(this);
}test(); // window object
In case of object literal with arrow function, this object doesn’t behave the way as in traditional function.
const obj = {
test() {
console.log(this);
}
}obj.test(); //{test: f} const obj = {
test:()=> {
console.log(this);
}
}obj.test(); //window object
The arrow function, doesn’t define arguments
i.e. they do not have arguments binding.
// Object with Arrow functionlet showData = {
showArg: ()=>console.log(arguments);
}showData.showArg(1,2,3);
// Uncaught ReferenceError: arguments is not defined
But you can easily access the arrow function arguments using a rest parameter ...args
.
// using rest parameterslet showData = {
showArg: (...args)=>console.log(args);
}myFunc.showArgs(1, 2, 3, 4); // [1, 2, 3, 4]
Thanks for Reading. For more information click on the below link.