Arrow functions were introduced with ES6 for shorter function syntax
It can be used as Constructor. it also best for non-method function
(param1, param2,.., paramN) => { statements }
var test = () => { return "test JS"; } test(); //output //test JS
var test = (name) => 'Name is '+name; test('Ashish'); //output //Name is Ashish //OR var test = name => 'Name is '+name; test('Ashish'); //output //Name is Ashish
var sum = (n1,n2) =>{ return n1+n2; } sum(2,3); //output //5
//default parameter with regular funstion function testReg(name='Ashish'){ console.log(name); } testReg(); //Ashish //default parameter with arrow funstion const testArrow = (name='Avanish')=>console.log(name); testArrow(); //Avanish //hoisting testReg(); function testReg(name='Ashish'){ console.log(name); } //Ashish testArrow(); const testArrow = (name='Avanish')=>console.log(name); //Uncaught ReferenceError: Cannot access 'testArrow' before initialization
const objectTest = ()=>({name:'Ashish'}); const person=objectTest(); console.log(person); //output //{name: "Ashish"}
//ES5 var person = { name:'Ashish', age:30, testHello : function(){ console.log(this.name); } }; person.testHello(); //Ashish //ES5 var person = { name:'Ashish', age:30, testHello : function(){ var self=this; setTimeout(function() { console.log(self.name); },10); } }; person.testHello(); //Ashish //ES6 var person = { name:'Ashish', age:30, testHello : function(){ setTimeout(() => { console.log(this.name); },10); } }; person.testHello(); //Ashish //ES6 var person = { name:'Ashish', age:30, testHello : ()=>{ console.log(this.name) } }; person.testHello(); //undefined