An array is an ordered group/collection of elements in JavaScript. Each array element has an index, which is a number that indicates where the element is located within the array. The array’s first element has an index of 0, the second element has an index of 1, and so on. Using the square brackets syntax, you can retrieve an array element by its index.
This article will illustrate the approaches to print the elements from an array in JavaScript.
How to Print Array Elements in JavaScript?
For printing elements from an array in JavaScript, use the following methods:
-
- for loop
- forEach() method
- console.log() method
Method 1: Print Elements From Array With JavaScript Using “for” Loop
Use the “for” loop for printing array elements in JavaScript. It iterates over the array and prints elements on a separate line as an output.
Syntax
Follow the given syntax for using the for loop:
// ......
}
Example
Create an array of numbers:
Iterate the array using “for” loop and print the elements on the console:
console.log(array[i]);
}
It can be seen that the elements of an array have been successfully printed on the console:
Note: You can also use a while() loop for printing array elements.
Method 2: Print Elements From Array With JavaScript Using “forEach()” Method
You can also use the “forEach()” method for printing elements of an array in JavaScript. It executes the specific function once for every array element.
Syntax
Use the following syntax for the forEach() method to print the elements from an array:
/* ... */
})
Example
Call the forEach() method and print every element on the console:
console.log(arrayElement);
});
Output
Note: You can also use for-of, for-in loops to print the elements from an array.
Method 3: Print Elements From Array With JavaScript Using “console.log()” Method
If you want to print the array in bracket notation, use the “console.log()” method. The console.log() method in JavaScript is a way to output data to the browser’s developer console. It can be used to print messages, debug code, and inspect variables and objects.
Syntax
Use the given syntax to print the elements from an array using the log() method:
It accepts an array as an argument.
Example
Pass the array as an argument in the log() method. This will print the complete array to the console:
It can be observed that the array has been successfully printed on the console in a bracket notation:
We have compiled all the essential information relevant to printing the elements from an array in JavaScript.
Conclusion
To print elements from an array in JavaScript, use the “for” loop, “forEach()” method, or the “console.log()” method. All the discussed ways print out each element of the array. Choose any of one from above discussed methods that best fits your use case and coding style. In this article, we illustrated the ways to print the array elements in JavaScript.