JavaScript Arrow function

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());
Output:-
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'));
Output:-
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();
Output:-
undefined undefined

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();
Output:-
John Taylor