ES6 Arrow Function Key Point 13.03.2018

It's a new feature that es6 provide us to write more sufficent and short anonymus function called "Arrow Function". There are lots of tutorial and blogs about it so i only speak of it's most beautiful feature for me is it's SCOPE .

I will show an example of it's benefit when used in a class as below;

let assume we have a class involves arrow function version and old function typed version:

HTML:

<button id="countUpBtn">Count Up</button>
<button id="getCountBtn">Get Count</button>
<div id="result"></div> 

JS:


class Counter {
constructor(){
this.count = 0;
}

countIt(){
return this.count++;
}

displayCount(container){
resultDiv.innerHTML = 'Loading...';

setTimeout(function(){
container.innerHTML = this.count;
},1000);

}
}

let counter = new Counter();


countUpBtn.onclick = () => console.log(counter.countIt());
getCountBtn.onclick = () => console.log(counter.displayCount(resultDiv));


Look at the setTimeout function, it looks at window Object to reach scope and class properties will be "undefined" inside it, but if we use;

 


displayCount(container){
resultDiv.innerHTML = 'Loading...';

setTimeout(() => {
container.innerHTML = this.count;
},1000);

}

Scope is now starts from my class which is the way i wanted. Have nice coding ;)