The for statement is used to iterate through a set, typically, an array or any iterable structure. It comes in four broad varieties:
- Conventional for: This includes the following:
- Syntax: for (initializer; condition; incrementer) {...}
- Usage: Typically used to iterate in a custom fashion through an indexed structure
- For...in: This includes the following:
- Syntax: for (let item in object) {...}
- Usage: Used to iterate through the keys of any object (typically used on plain objects)
- For...of: This includes the following:
- Syntax: for (let item of iterable) {...}
- Usage: Used to iterate over an iterable (typically array-like) structure
The type of for construct you'll employ will depend on what exactly you wish to iterate over. For straightforward indexed and array-like structures, for example, the for...of construct will be most useful. We'll go over each of these constructs to explore use cases and potential challenges.