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(); });
forEach() is an inbuilt TypeScript function which is used to calls a function for each element in the array. Parameter: This method accepts two parameter as mentioned above and described below: callback : This parameter is the Function to test for each element.
JavaScript Array forEach()The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
The angular. forEach() Function in AngularJS is used to iterate through each item in an array or object. It works similar to the for loop and this loop contains all properties of an object in key-value pairs of an object.
Check out this example:
var method = a => a+1;
method
is a var that holds a reference to a function.a
is the input param.a+1
is the methods body and return type.
Typescript will transpile this into:
var method = function (a) { return a + 1; };
Check out the typescript playground example and you will understand the concept pretty fast.
In your example fns is an array of functions.
doing fns.forEach(fn=>fn());
means execute each method in the fns array.
fn => fn()
is a function definition, in C# they are called Lambda expressions and it is just syntactic sugar for the same function (fn) { return fn(); }
.
fn
is the input parameter, and =>
defines it as a function and the fn()
is the return value.
Another example is
var add = (a,b) => a + b;
is the same as
function add(a, b) {
return a + b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With