- JavaScript For Loop
- Instead of writing:
- You can write:
- Different Kinds of Loops
- The For Loop
- Example
- Expression 1
- Example
- Example
- Expression 2
- Expression 3
- How to Loop Through an Array in JavaScript – JS Iterate Tutorial
- Here’s an interactive scrim about how to loop through an array in JavaScript:
- What are Loops in JavaScript?
- How to Loop Through an Array with a While Loop in JavaScript
- How to Loop Through an Array with a do…while Loop in JavaScript
- How to Loop Through an Array with a for Loop in JavaScript
- How to Loop Through an Array with a for…in Loop in JavaScript
- How to Loop Through an Array with a for…of Loop in JavaScript
- How to Loop Through an Array with a forEach Loop in JavaScript
- Wrapping Up
- Javascript loop through all
- # Loop through all DOM elements using JavaScript
- # Breaking out of the loop if a condition is met
- # Iterating only over the elements contained in the body tag
- # Additional Resources
JavaScript For Loop
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + «
«;
text += cars[1] + «
«;
text += cars[2] + «
«;
text += cars[3] + «
«;
text += cars[4] + «
«;
text += cars[5] + «
«;
You can write:
Different Kinds of Loops
JavaScript supports different kinds of loops:
- for — loops through a block of code a number of times
- for/in — loops through the properties of an object
- for/of — loops through the values of an iterable object
- while — loops through a block of code while a specified condition is true
- do/while — also loops through a block of code while a specified condition is true
The For Loop
The for statement creates a loop with 3 optional expressions:
Expression 1 is executed (one time) before the execution of the code block.
Expression 2 defines the condition for executing the code block.
Expression 3 is executed (every time) after the code block has been executed.
Example
From the example above, you can read:
Expression 1 sets a variable before the loop starts (let i = 0).
Expression 2 defines the condition for the loop to run (i must be less than 5).
Expression 3 increases a value (i++) each time the code block in the loop has been executed.
Expression 1
Normally you will use expression 1 to initialize the variable used in the loop (let i = 0).
This is not always the case. JavaScript doesn’t care. Expression 1 is optional.
You can initiate many values in expression 1 (separated by comma):
Example
And you can omit expression 1 (like when your values are set before the loop starts):
Example
Expression 2
Often expression 2 is used to evaluate the condition of the initial variable.
This is not always the case. JavaScript doesn’t care. Expression 2 is also optional.
If expression 2 returns true, the loop will start over again. If it returns false, the loop will end.
If you omit expression 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.
Expression 3
Often expression 3 increments the value of the initial variable.
This is not always the case. JavaScript doesn’t care. Expression 3 is optional.
Expression 3 can do anything like negative increment (i—), positive increment (i = i + 15), or anything else.
Expression 3 can also be omitted (like when you increment your values inside the loop):
How to Loop Through an Array in JavaScript – JS Iterate Tutorial
Joel Olawanle
An array is a single variable used to store elements of different datatypes so that they can be accessed through a single variable.
It is an ordered list of values, and each value is referred to as an element, which is specified by an index.
Knowing that these single variables contain a list of elements, you might want to create a list of these elements so that you can perform individual functions with them and much more. This is where the loop comes into play.
Here’s an interactive scrim about how to loop through an array in JavaScript:
What are Loops in JavaScript?
A loop is a type of computer program that allows us to repeat a specific operation a predetermined number of times without having to write that operation individually.
For example, if we have an array and want to output each element in the array, rather than using the index number to do so one by one, we can simply loop through and perform this operation once.
There are numerous methods for looping through an array in JavaScript. In this article, we will go over the most commonly used so you can learn different approaches and understand how they work.
We will use the following array for this article:
const scores = [22, 54, 76, 92, 43, 33];
How to Loop Through an Array with a While Loop in JavaScript
You can use a while loop to evaluate a condition that is enclosed in parenthesis () . If the condition is true , the code inside the while loop is executed. If it is false , the loop is terminated.
If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.
Let’s now use the while loop method to loop through the array:
This will return each element in our array one after the other:
In the loop above, we first initialized the index number so that it begins with 0 . Then the number will continue to increase and output each element until the condition we set returns false, indicating that we have reached the end of the array. When i = 6 , the condition will no longer be executed because the array’s last index is 5 .
How to Loop Through an Array with a do…while Loop in JavaScript
The do. while loop is nearly identical to the while loop, except that it executes the body first before evaluating the condition for subsequent executions. This means that the loop’s body is always executed at least once.
Let’s perform the same loop with the do…while loop to see how it works:
This will return each element in our array:
As previously stated, this will always run once before evaluating any condition set. For example, if we set the index i to 6 and it is no longer less than scores.length , the body of the loop will run first before checking the condition:
This will return a single undefined because we do not have an element in the array of index 6 but as you can see it ran once before stopping.
How to Loop Through an Array with a for Loop in JavaScript
The for loop is an iterative statement that checks for certain conditions and then executes a block of code repeatedly as long as those conditions are met.
We don’t need to initialize the index first when using the for loop method because the initialization, condition, and iteration are all handled in the bracket, as shown below:
This will return all the elements as other methods have done:
How to Loop Through an Array with a for…in Loop in JavaScript
The for…in loop is an easier way to loop through arrays as it gives us the key which we can now use to get the values from our array this way:
This will output all the elements in our array:
How to Loop Through an Array with a for…of Loop in JavaScript
The for. of Loop iterates over iterable objects such as arrays, sets, maps, strings, and so on. It has the same syntax as the for. in loop, but instead of getting the key , it gets the element itself.
This is one of the easiest methods for looping through an array and was introduced in later versions of JavaScript ES6.
This gets each element of our array and we no longer need to make use of the index to get each element of our array:
How to Loop Through an Array with a forEach Loop in JavaScript
The array method forEach() loop’s through any array, executing a provided function once for each array element in ascending index order. This function is known as a callback function.
This is a more advanced method that can do much more than simply loop through each element, but you can also use it to loop through this way:
You can write this in one line this way:
scores.forEach((score) => console.log(score));
And this will give us the same output as all previous methods:
Wrapping Up
In this article, we looked at six different/standard methods for looping through an array.
It is critical that you understand all of these methods and then determine which method is preferable for you, cleaner to use, and easier to read.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
Javascript loop through all
Last updated: Jan 12, 2023
Reading time · 2 min
# Loop through all DOM elements using JavaScript
To loop through all DOM elements:
- Use the getElementsByTagName() method to get an HTMLCollection containing all DOM elements.
- Use a for. of loop to iterate over the collection.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div>Box 1div> div>Box 2div> div>Box 3div> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const allElements = document.getElementsByTagName('*'); // ✅ Loop through all elements (including html, head, meta, scripts) for (const element of allElements) console.log(element); > console.log('--------------------'); // ✅ Loop through all elements in body const allInBody = document.querySelectorAll('body > *'); for (const element of allInBody) console.log(element); >
The document.getElementsByTagName method returns an HTMLCollection containing the elements with the provided tag name.
If the method is passed an asterisk * as a parameter, it returns a collection containing all DOM elements.
We used a for. of loop to iterate over the collection.
# Breaking out of the loop if a condition is met
Note that you can use the break keyword to break out of a for loop if a certain condition is met.
Copied!const allElements = document.getElementsByTagName('*'); for (const element of allElements) console.log(element); if (element.textContent === 'Box 2') break; > >
The selector above contains all of the DOM elements, including the html element, the head element, etc.
# Iterating only over the elements contained in the body tag
If you only need to iterate over the elements contained in the body tag, use the document.querySelectorAll() method.
Copied!const allInBody = document.querySelectorAll('body > *'); for (const element of allInBody) console.log(element); >
The document.querySelectorAll method takes a string containing a CSS selector as a parameter and returns a NodeList containing the matching elements.
We used a for. of loop to iterate over the NodeList , however, you can also use the NodeList.forEach method.
Copied!const allInBody = document.querySelectorAll('body > *'); allInBody.forEach(element => console.log(element); >);
The function we passed to the forEach() method gets called with each element in the NodeList .
The querySelectorAll() method takes one or more comma-separated selectors.
The following example selects all elements with classes my-class and your-class .
Copied!const elements = document.querySelectorAll( '.my-class, .your-class' ); elements.forEach(element => console.log(element); >);
You can pass as many comma-separated selectors to the method as necessary.
This might be a more efficient solution if you don’t need to iterate over every single element in the DOM.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.