Table of contents
What is a loop?
A loop is used to iterate over a block of code repeatedly until the condition inside it is true. If the condition inside is false or becomes false, the loop will be terminated. Every programming language has this feature, the only thing is that the syntax changes from one programming language to another.
JavaScript is a programming language whose syntax is closest to the C programming language with dynamic typing. In JavaScript, we can write loops in many different ways ( probably in too many ways? ) like for loop, for-of loop, for-in loop, forEach loop, while loop and do-while loop.
The full platter:
- for loop
This is the OG of all loops. There are three sections inside a for loop namely initialization, condition and increment/decrement.
- for-of loop
This loop creates a loop over iterable elements like arrays, objects, strings etc.
- for-in loop
The for-in loop allows us to access the property of an object without knowing the specific name of that object's property. A different item is assigned to a variable on each iteration.
- forEach loop
This is more of a method rather than a traditional loop.
forEach()
method iterates over all items of an array automatically.forEach()
method calls a function for each element in an array but it will not be executed for an empty array element. Array elements or strings can be iterated over usingforEach()
method.
- while loop
This loop iterates a block of code til the condition inside the while statement is true. If we aren't careful about the condition inside the while statement, we can run into problems like an infinite loop. That's why it is advisable to use increment/decrement variables inside the while loop.
- do-while loop
The do-while loop is executes the block of code inside it at least once. We shouldn't forget to add an increment/decrement variable inside the block otherwise we will run into the same problem of infinite loop again just like we did in the while loop.