Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript/JavaScript forEach call

Tags:

typescript

I am having trouble understanding this bit of code:

stringsArray.forEach(s => {
    for (var name in validators) {
        console.log('"' + s + '" ' +
            (validators[name].isAcceptable(s) ?
                ' matches ' : ' doesnt match ') + name);
    }
});

in particular, the s => { ... part is mysterious. It looks like s is being assigned to the next string in the array on each loop. But what is the => part meaning? It's related to lambdas I think, but I am not following.

like image 427
pitosalas Avatar asked Jun 20 '15 01:06

pitosalas


1 Answers

Yeah it's a lambda (for example, similar to ECMAScript6 and Ruby, as well as some other languages.)

Array.prototype.forEach takes three arguments, element, index, array, so s is just the parameter name being used for element.

It'd be like writing this in regular ECMAScript5:

stringsArray.forEach(function(s) {
    for (var name in validators) {
        console.log('"' + s + '" ' +
            (validators[name].isAcceptable(s) ?
                ' matches ' : ' doesnt match ') + name);
    }
});

In the above example, you didn't show the whole code, so I assume validators is just a plain object {}.

The syntax for the example you gave is actually identical to the ES6 syntax.

Check out this example from the TypeScript handbook:

example

like image 136
Josh Beam Avatar answered Sep 18 '22 17:09

Josh Beam