The 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); } }

The code works fine, but we add extra requirement wait 1 second until the invoice is created like an ajax response.

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

But something is going wrong, because the invoiceId is undefined and if we have a global variable with the same name also.

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

This shows 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, the code should be messy, for these cases the Arrow functions come to rescue us 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 #es6