How to Print Array elements on a Webpage

When you are working with arrays in JavaScript, you will want to print out the elements of your array.
In a browser environment, you have two options, using the console.log()
function or writing it to the DOM.
In this post, we'll see examples of the two best ways to print out your array.
Using the console.log()
function
The easiest way to print out an array is to use the console.log()
function.
You can loop through each element, printing it out one by one.
First, let's start with our array:
const array = [1, 2, 3, 4, 5];
Then, let's loop through the array and print out each element:
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
1
2
3
4
5
Writing the results to the DOM
To write your array to the DOM, you will first need to convert your array to a string.
Thankfully, we can take advantage of the JSON.stringify()
function to do this.
We can have the JSON.stringify()
function convert our array to a string, and then we can write the string to the DOM.
const array = [1, 2, 3, 4, 5];
const string = JSON.stringify(array);
document.querySelector(".output").innerHTML = string;
[1, 2, 3, 4, 5]
Here's a full example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Array example</title>
</head>
<body>
<pre class="output"></pre>
<script>
const array = [1, 2, 3, 4, 5];
const string = JSON.stringify(array, null, 4);
document.querySelector(".output").innerHTML = string;
</script>
</body>
</html>
[
1,
2,
3,
4,
5
]
You've successfully printed out your array to the DOM!
Conclusion
In this post, we looked at examples of the two best ways to print out your array.
The two ways are using the console.log()
function and then writing the results directly to the DOM.
Hopefully, this post has been useful to you!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!