Loops in JavaScript
Explore the fundamentals of loops in JavaScript, including how loop conditions control repeated execution of code blocks. Learn the syntax and application of various loop types such as while, do-while, for, for-in, for-of, and forEach. Understand how to implement loops that efficiently iterate until a condition fails, and recognize the importance of avoiding infinite loops in your programs.
We'll cover the following...
Loops need a dependent condition as it continues to iterate the same set of instructions until the condition fails.
The illustration gives an overview of the look of a program flow for a loop. Let’s list the properties.
Loops features
A program loop has the following properties:
- A condition which can be
trueorfalse - A program block that is executed while the condition is
true
With these features in mind, let’s map them to the corresponding JavaScript syntax.
Basic loop syntax and semantic
We saw that a loop needs to have a condition and a program block where all the necessity instructions reside. Below shows an outline of a loop in JavaScript:
Here, a loop starts with a LoopToken token, followed by a condition in parentheses, and concluding with a set of instructions encapsulated within the brackets.
Let’s write a small program that would count till five for us in a while loop where the while is a LoopToken in JavaScript.
Write a small program that can count to five in a while loop where the while is a LoopToken.
In the above program, we initialize the variable count by assigning it to 0. Our loop is set to keep running while the count variable is assigned to a value less than five on line 2. In the loop’s program block, we increment the count variable and print its value at line 3. With the prefix-increment operator ++.., the variable is incremented. The new value is used by console.log(). We see from the result that the program continues to print the updated values of count and terminated when count is assigned to a value of five.
The key takeaway is that the loop continues while the condition is true and terminates as soon as the condition is false. If the count variable was not updated within the program block or was updated in reverse order, the loop would have not stopped executing or would have taken a very long time to terminate. A loop that does not terminate is called an infinite loop.
Note: The setting of loops is similar to that of a conditional, except there is only one program execution block here and it continues to execute while the condition is true. In conditionals, you could have multiple by chaining conditionals.
Types of JavaScript loops
Below is a list of all loops in JavaScript:
while– While loopdo/while– Do - While loopfor– For loopfor/in– For - in loopfor/of– For - of loopforEach– For each loop
Each of these offers of its own convenience.