How To Print Array In JavaScript Using For Loop
In this article, you will look at how to print array in javascript using for loop, you will also look at the different varieties of loops to print the array.
4 ways to print array in javascript using for loop
Regardless of whether you are programming, developing something, or presenting data on a browser you continually need to print the data of the array.
We have discussed 4 different ways to print array in javascript.
- Using for loop
- Using forEach loop
- Using for...in loop
- Using for...of loop
Table Of Contents
1. Print array using for loop
Every element in an array has an index value that defines the location of an element in an array. For example, the first element of the array has an index value of 0, the second element 1, the third element 2, and so on.
To access the first element you can write array_name[0], for the second element array_name[1], and so on.
Now to print the array using for loop run a for loop for a number of times as a number of elements in the array and use the iterator each time to access the array element and print it one by one.
Here is the code to print the array in javascript.
Example
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // here i represents index
}
2. Print array using forEach loop
forEach() is a javascript method that executes a given function once for each element of the array.
Here you want to print the array so provide a function to print the array.
The function accepts the array element as the first array (for each execution of loop element updates to the next element). So you can directly print this element.
Here is the code to print the array in javascript using a forEach loop.
3. Print array using for...in loop
The for...in the loop is used to iterate over the properties of an object, where the loop provides a key for each property of the object.
Since the array is also an object in javascript we can use this to iterate through each element and print it. Here key provided will be the index of the array.
You can simply use the key and access the array element by array_name[key].
Here is the code to print the array using for...in the loop.
4. Print array using for...of loop
The for...of loop iterates over an iterable object like an array, string, map, set, array-like objects, etc.
It creates a custom iteration hook that executes for each distinct property of the object. Here the object is an array so the property here is the element itself.
You can simply print the property as an array element. Here is the code to print the array using for...of the loop.
Conclusion
We have discussed 4 different ways to print array using for loop in javascript with various examples. Among these 4 methods, a forEach method is a modern approach and also it gives more flexibility, power, and control over the array and its elements.