I'm doing a tutorial on lexical scope handling by Typescript and I've come across the use of a function which I have never seen before. Which looks like an empty function in a forEach statement. In typescript it looks like this:
fns.forEach(fn=>fn());
In javascript it looks like:
fns.forEach(function (fn) { return fn(); });
I've never seen a function used like this. Can someone explain how this works? To be specific, what is fn=>fn() actually executing. In reference to the code below, is it executing the fns.push or for loop? If it is the For Loop there's no reference to this so how does it know?
Below is the full code:
TypeScript:
var fns = [];
for(var i=0;i<5;i+=1){
fns.push(function(){
console.log(i);
})
}
fns.forEach(fn=>fn());
JavaScript
var fns = [];
for (var i = 0; i < 5; i += 1) {
fns.push(function () {
console.log(i);
});
}
fns.forEach(function (fn) { return fn(); });
varin theforloop tolet. Also, although not relevant to your question, arrow functions are not TypeScript specific--they are just plain old ES6.