() => Arrow functions are more than a fancy or short way to write functions.

Yesterday, I found a good reason to use arrow functions, sometimes I said the arrow functions is a fancy or shorter way to write functions but this is not the only benefit, the Arrow functions can keep the scope of his object without going to global window, I will explain with code.

let paymentmanager = { invoiceId: 1, CloseInvoice: function(){ console.log("close invoice" + this.invoiceId); } }

this code works fine, but if we add a simple extra requirement like a function for wait 1 second until the invoice is created or ajax response.

let paymentManager = { invoiceId: 1, CloseInvoice: function(){ setTimeout(function() { console.log("close invoice" + this.invoiceId); },1200); } }

Something going wrong because the invoiceId is undefined, but if we have a global variable with the same name.

let invoiceId = 3 let paymentManager = { invoiceId: 1, CloseInvoice: function(){ setTimeout(function() { console.log("close invoice" + this.invoiceId); },1200); } }

It another invoiceId because “this.” is targeting the global window object, so now we had a real problem.

We can use var self = this to keep but if we have few functions like ajax call and another function to handle the response, this should be messy, for these cases arrow functions come to resolve and allow write a shorter and elegant code.

let InvoiceId = 100; let InvoiceManageArrow = { InvoiceId: 21000, Pay() { setTimeout(() => { console.log("Pay into InvoiceId: " + this.InvoiceId); }, 1200); } }; #Javascript