16

I really like using the foreach construct for "for loops" in C#. I think it's very clean, efficient and readable.

Is there a similar construct in TypeScript? For example, instead of this:

setAuthorFilters(selectedAuthors)
{
    selectedAuthors.forEach(x => this.setAuthorFilter(x));
    this.updateUrl();        
}

setAuthorFilter(selectedAuthor)
{
    this.vm.SelectAuthors = this.vm.SelectAuthors.filter(x => x.id !== selectedAuthor.id);
    this.vm.PreviousSelectedAuthors = this.vm.CurrentSelectedAuthors.slice();
    this.vm.CurrentSelectedAuthors.push(selectedAuthor);
}

I'd like to do this:

setAuthorFilters(selectedAuthors)
{
    foreach(var selectedAuthor in selectedAuthors)
    {
        this.vm.SelectAuthors = this.vm.SelectAuthors.filter(x => x.id !== selectedAuthor.id);
        this.vm.PreviousSelectedAuthors = this.vm.CurrentSelectedAuthors.slice();
        this.vm.CurrentSelectedAuthors.push(selectedAuthor);
    }
    this.updateUrl();        
}
0

1 Answer 1

20

Yes, the for ... of

E.g.

for(let author of authors)
{ 
  ... 
}

Because you're using TypeScript, this also works in IE. See https://basarat.gitbooks.io/typescript/content/docs/for...of.html :

For pre ES6 targets TypeScript will generate the standard for (var i = 0; i < list.length; i++) kind of loop.

In plain Javascript, so without Typescript, this isn't supported in IE (source)

Update: for scoping is let more similar to C# than var. Updated the example.

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

2 Comments

Do note that for .. of .. can be used with JS Iterables, while the pre-ES6 translation will not work with those.
@Kroltan also worth noting that the compiler has a downlevelIteration option that enables support even in ES3 environments.

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.