Loops allow developers to write repetitive code efficiently without duplicating lines of code.
JavaScript loops allow developers to tell JavaScript to repeat themselves without becoming bored. If JavaScript conditional statements are about decision-making, loops are about taking the same actions repeatedly but quickly.
Can you think of any activity you have performed manually where you did the same things over and over? Updating every item in a table, looking at each user in a database, creating animations for every single item on a webpage. Performing such activities individually is boring. Loops help remove the tedium. They state, “Repeat this line of code once per item in this group,” or “Continue to repeat this line of code until we reach a point at which this condition no longer exists.”
If loops were absent from your programming projects, your applications could either be extremely small or extremely redundant. By using loops, you write a piece of logic only once, and JavaScript does the rest of the repetition.
Let’s discuss five common JavaScript loop patterns that you will use continuously.
1. The for Loop: Basic Counting Control
The for loop is probably the most well-known type of JavaScript loop. It’s useful when you’re aware of how many times you’ll need to perform an action, or when you want to increment or decrement a value by a specific amount.
A for loop consists of three elements within its parentheses that are separated by semi-colons. First, you define a counter variable. Next, you determine what conditions will continue allowing the loop to execute. Lastly, you describe how much you’d like to increment/decrement your counter variable after each pass through the loop.
While there are other types of loops available, the for loop allows you to have the most precision. You can count from 0-9, from 10-1, or even only include every third item in the sequence. You can also utilize your counter variable within the body of your loop to reference the value stored in an array position or to compute another value.
One popular application is looping through an array with indexes. Arrays are 0-based indexed, therefore you begin your counter at 0 and finish before your array’s length. Although the following is a common usage pattern for accessing an array via its index, be careful regarding your loop termination condition; if you incorrectly use <= instead of < you may inadvertently cause additional executions beyond the size of your array, potentially causing issues.
2. The while Loop: Continue Execution Until a Condition Is Satisfied
In some instances, you do not know beforehand how often you want to execute a loop. Perhaps you are waiting for user input or processing data until a certain threshold or value exists. At these points, the while loop provides the best solution.
The while loop verifies a condition prior to executing each pass through the loop. So long as this condition remains true, the loop continues to execute the specified block of code. Once this condition becomes false, the loop ceases execution. Therefore, this makes while loops suitable for use whenever the quantity of passes depends upon something that can change during the course of the loop.
A critical aspect related to using while loops is ensuring that some component of your loop causes the condition to become false eventually. An infinite loop occurs when your condition never becomes false due to failure to modify the variable affecting the condition, resulting in continued execution indefinitely. Be mindful of this occurrence and take measures to prevent it from happening.
While loops are particularly beneficial when working with continuous flows of data (reading), retrying operations until successful, and game development where you continually run until a player either loses or wins. They offer flexibility but require maintaining proper condition updates during operation.
3. The do…while Loop: Run Code Block Before Checking Conditions
The do…while loop is a variant of the while loop with one important distinction, it always executes the code block at least once, then checks the condition after completion. Thus, it ensures that at least one pass occurs regardless of whether the initial condition is satisfied.
Why would anyone want this? There are certainly scenarios in which you wish to take some action prior to knowing whether you will continue or not. A good example is requesting input from a user, and continuing to request input until he/she supplies valid input. The first prompt is always executed, and then based on whether the response is valid or not determines whether another loop is initiated.
While the do…while loop is utilized far less frequently than for or while loops, it is a valuable asset when you require that at least one execution occur prior to evaluating your condition.
4. The for…of Loop: Modern Array & Iterable Processing
For…of loops were added in recent versions of JavaScript as a cleaner alternative to using a traditional for loop for traversing through arrays and other iterable objects (strings, Maps, Sets etc). Rather than having to manage an index counter yourself, you receive each item sequentially through the iterable object.
The for…of loop is easier to read and less prone to error than utilizing a traditional for loop when you don’t need access to an index for each item. Simply declare a variable that will hold each item, type “of”, followed by the iterable object containing items you want to traverse through in the loop. The loop automatically takes care of traversal for you.
For…of loops are ideal for processing individual elements in lists when you only care about their values rather than their locations. Need to display all products in a shopping cart? Utilize for…of. Want to print each character in a string? for…of functions perfectly well. Want to traverse through a Map of keys-values? for…of delivers each entry.
The only constraint associated with for…of loops is that they do not provide direct access to an index for each item. If you need to know the location of each item in an array, choose a traditional for loop or consider utilizing the entries() method to obtain both index and value.
5. The for…in Loop: Accessing Property Names Of An Object
When needing to traverse through properties of an object, for…in loops serve as the ideal option. They permit traversal of all properties that are enumerable on an object (including those properties inherited from its prototype chain).
This is distinct from for…of which operates on iterable values since objects are non-enumerable values unless explicitly marked otherwise; thus for…of will not operate on plain objects. for…in returns each property name (key) separately from the corresponding value by referencing it with that key.
Caution with regard to utilizing for…in loops: they traverse through all properties including inherited ones whereas typically users desire only enumeration of an object’s own enumerable properties. Users can easily add a check similar to object.hasOwnProperty(key) to restrict enumeration to only own properties; however since ordering of enumeration is not guaranteed consistent across browsers/engines be wary of utilization for complex objects.
Using for…in loops with simple objects is fairly straight-forward when needing to process each key-value pair; however, do not utilize for…in with arrays since they enumerate array properties (not simply numeric indices); such behavior can lead to undesirable outcomes. Utilize for…of or traditional for loops with arrays instead.
Combining Them All
In total, these five basic JavaScript loop formats – for, while, do…while, for…of and for…in provide full flexibility with regards to iterative control in your applications.
Begin with classic for loops for counting and array indexing. Use while loops when you do not know how many times you will need to repeat something. Choose do…while loops when you want at least one execution guaranteed. Use for…of loops when wanting clean and modern iteration over arrays/strings/iterables/etc. Select for…in loops for iterating over object property names but be cognizant of potential inheritance.
The more frequently you practice using these different types of loops, the more second nature it will become selecting the correct format for handling each particular scenario. Eventually you will focus on solving problems rather than thinking about how to write your loops.
Checklist For Mastery Of JavaScript Loops
Below is a checklist designed to assist you in organizing your learning efforts in mastering JavaScript loops:
- Use for loops when knowing number of repetitions. Perfect for counting/indexes and high level control.
- Use while loops when number of repetitions depend on changing condition. Good when unknown/variable length repetition needed.
- Use do…while loops when code block needs run at least once. Ideal when performing input validation loops.
- Use for…of loops for array/string/Map/Set/etc iteration. Cleaner/easier/safer than traditional for loops when index access NOT required.
- Use for…in loops for iterating over object property names. Add hasOwnProperty checks in order to exclude inherited properties.
- Do not generate infinite loops. Always ensure some component of your loop modifies enough of your variable(s) involved with terminating your loop’s condition.
- Do not alter arrays during iteration with for…of. Doing so may result in skipping/processing/re-processing items in array, Use traditional for loop if modification during iteration desired.
- Be mindful of performance considerations when using large numbers of iterations. Operations contained within loops are executed numerous times. Maintain efficiency wherever possible.
To learn more about these topics further refer to MDN’s Loops and Iteration Guide which includes extensive documentation along with examples. Additionally JavaScript.info contains an excellent beginner-friendly section covering loops with practical explanations that illustrate concepts clearly.
New to HTML? Start Here: HTML Tutorial for Beginners: Your Complete Introduction to HTML Basics
New to CSS? Start Here: CSS Introduction: Master 5 Core Concepts Easily
New to JavaScript? JavaScript Introduction: 5 Proven Steps to Learn JS
[INSERT_ELEMENTOR id=”122″]

