pitosalas
pitosalas

Reputation: 10852

TypeScript/JavaScript forEach call

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.

Upvotes: 10

Views: 53890

Answers (1)

Josh Beam
Josh Beam

Reputation: 19772

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

Upvotes: 16

Related Questions