How to Print Array elements on a Webpage

Updated onbyAlan Morel
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:

JAVASCRIPT
const array = [1, 2, 3, 4, 5];

Then, let's loop through the array and print out each element:

JAVASCRIPT
const array = [1, 2, 3, 4, 5]; for (let i = 0; i < array.length; i++) { console.log(array[i]); }
BASH
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.

JAVASCRIPT
const array = [1, 2, 3, 4, 5]; const string = JSON.stringify(array); document.querySelector(".output").innerHTML = string;
BASH
[1, 2, 3, 4, 5]

Here's a full example:

HTML
<!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>
BASH
[ 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.