Arrow Function also called as “fat arrow function”, is the way of writing a function by reducing code.
Regular function:
const getSum = function(a, b){
return a + b;
}
Arrow function:
const getSum = (a, b) => a + b;
In the above two examples, we can see ‘Arrow Function’ allows us to use the fat arrow operator(=>) to define a function. Also, we do not need to use curly braces if there is only one line code inside the function & it will return the value.
Also, no need to use the ‘return’ keyword to return value. If we write the ‘return’ keyword in one line arrow function, it will show an error.
N.B.: If we want to write multiple line code in an arrow function then we have to use curly braces and inside have to write the ‘return’ keyword to return a value.
In one line:
const greeting = () => "Hello, there!";
In multi-line:
const greeting = (name,gender) => {
let msg;
if(gender === "male"){
msg = "Hello, sir!";
}else if(gender === "female"){
msg = "Hello, madam!";
}
return msg;
}
Omitting parentheses:
We can just omit parentheses if there is only one parameter in the arrow function. But, it is not applicable if there is 2 parameter.
For one parameter in arrow function:
const greeting = name =>
Hello, ${name}!;
Or, can write
const greeting = (name) =>
Hello, ${name}!;
For two or more parameters:
const greeting = (fname,lname) =>
Hello, ${fname} ${lname}!;
‘this’ keyword in regular function & arrow function:
‘this’ keyword defines the outer object. But, the difference between regular function and arrow function.
In the regular function, see the example first:
businessStudies = {
name: "Business Studies",
subjects: ["Accounting","Finance","Marketing"],
printMessage: function(){
this.subjects.forEach(function(subName){
console.log(`${subName} is a subject of ${this.name}`);
})
}
}
In this example, printMessage method is inside businessStudies object. So, ‘this’ keyword of printMessage method will define the whole businessStudies object. Because printMessage method is a custom method of businessStudies.
But, the ‘this’ keyword inside the callback function of forEach loop will not be defined by the businessStudies object. Because it is not a custom method inside our object. It is a built-in method. So, the ‘this’ keyword inside the regular callback function of the forEach loop will define the whole document(window or global).
In the arrow function, see the example:
businessStudies = {
name: "Business Studies",
subjects: ["Accounting","Finance","Marketing"],
printMessage: function(){
this.subjects.forEach((subName) => console.log(`${subName} is a subject of ${this.name} student`))
}
}
Above example, ‘this’ keyword of inside arrow callback function of forEach loop will define the businessStudies object. Because the arrow function deals with the direct outer object. It doesn’t matter that we are using a build-in method or a custom method.
My Portfolio Website: https://habibullahftl.web.app/
Top comments (0)