Iterating Using Different for loops in JavaScript
How for, for…in and, for…of loops work and how to use them effectively in JavaScript
JavaScript has three different types of for
loops, so there may be slight confusion for someone new to JavaScript on which kind of for
loop to use for a given scenario. So, here you will see:
- How a
for
loop works and how to use it. - How a
for…in
loop works and how we can use it to iterate over enumerable objects. - How a
for…of
loop works and how we can use it to iterate over iterable objects. - When to use each of them.
- The main difference between
for…in
andfor…of
.
We will go through each of them in detail.
1. for
for statement is used to create a loop that runs based on the given three parameters separated by a semicolon. The parameters are followed by a block of statements enclosed in parenthesis, over which we need to loop over.
variable initialization: Variable declarations at the start of the loop happen here, generally…