Javascript Arrow function came into ES6 (ECMAScript 6). Arrow functions don’t bind this keyword to the object.
Arrow functions are best for callbacks or methods like map, reduce, or forEach, etc.
in Arrow function do not write function keyword.
Arrow function without parameter
Syntax:-
arrow_function_name:()=>{
return 'Hello';
}
Example:- Suppose, you have a greetings object and that has the say_hello method without parameter..
let greetings={
say_hello:()=>{
return 'Hello';
}
}
console.log(greetings.say_hello());
Arrow function with parameters
Syntax:-
arrow_function_name:(param1, param2)=>{
return param1+param2;
}
Example:- Suppose, you have a greetings object and that has the say_hello method with parameter friend_name.
let greetings={
say_hello:(friend_name)=>{
return 'Hello '+friend_name;
}
}
console.log(greetings.say_hello('Rom'));
Arrow function do not bind this keyword to the object
Suppose, you have employee object and you want to call first_name and last_name through this keyword in full_name method then output will show undefined.
let employee = {
first_name: 'John',
last_name:'Taylor',
full_name: () => {
console.log(this.first_name+' '+this.last_name)
}
}
employee.full_name();
Simple function bind this keyword to the object
Suppose, you have employee object and you want to call first_name and last_name through this keyword in full_name method then output will show first_name and last_name values.
let employee = {
first_name: 'John',
last_name:'Taylor',
full_name: function () {
console.log(this.first_name+' '+this.last_name)
}
}
employee.full_name();
JavaScript Arrow function – Interview Questions
Q 1: What is an arrow function?
Ans: Shorter syntax for functions.
Q 2: Syntax?
Ans: () => {}.
Q 3: Does Arrow have its own this?
Ans: No.
Q 4: Can an arrow function be a constructor?
Ans: No.
Q 5: Advantage?
Ans: Cleaner syntax.
JavaScript Arrow function – Objective Questions (MCQs)
Q1. Which symbol is used to define an arrow function?
Q2. Arrow functions were introduced in ______.
Q3. Arrow functions do NOT have their own ______.
Q4. Arrow functions handle this by ______.
Q5. Which syntax is correct for a single parameter?