10

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.

1 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks... Still a little confused... Note that I am quite proficient in Ruby but not in JS. I am learning TS instead because it seems like a more solid foundation for me... is "s => { }" passing a lambda as the first argument to for_each? If so, how can s appear again in the body of the lambda itself? That's where I am stumped (for now.) Thanks!
@pitosalas, TypeScript is icing on top of JavaScript. I think it's probably a bad idea to learn TypeScript first, and not the other way around. Have you read the documentation for .forEach? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
well I know a little js (and I am reading eloquent js in parallel) so other than some trickiness here I feel pretty comfortable. But I will follow the link you point to and study that too. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.