How to print a JavaScript array to the DOM

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: May 13, 2022.

Raw printing of the array as a string

Appending a JavaScript array directly to the DOM causing it to be silently converted to string format before being appended:

/* Printing an array directly to the DOM */

const array = ["JavaScript", "TypeScript", "React"];

document.body.append(array);

// "JavaScript,TypeScript,React"

The same result is achieved by using the toString() method on the array and then appending it to the DOM:

/* Converting an array to a string to print to the DOM */

const array = ["JavaScript", "TypeScript", "React"];

const arrayString = array.toString();

document.body.append(arrayString);

// "JavaScript,TypeScript,React"

Adding spacing between elements with join()

To add spacing between the elements, use the join method, passing in the content to be concatenated between each element:

/* Add spacing between array elements with array.join() */

const array = ["JavaScript", "TypeScript", "React"];

const arrayJoined = array.join(', ')

document.body.append(arrayJoined);

// "JavaScript, TypeScript, React"

Printing in grammatically correct format

To print the list in readable format, "and" should appear before the final element in the list.

This can be achieved by adding "and " before the final array element, joining them and removing the final comma:

/* Print contents of an array as a grammatically correct list */

let array = ["JavaScript", "TypeScript", "React"];
 
// Sets final array element to "and " + final array element
if (array.length > 1) {
   array[array.length-1] = "and " + array[array.length-1];
}
console.log(array); // ["JavaScript","TypeScript","and React"]

// Join array (including and)
let stringJoined = array.join(', ');
console.log(stringJoined); // "JavaScript, TypeScript, and React"
 
// Slice joined array before and after final comma and concatenate the results
if (array.length > 1) {
   let firstPart = stringJoined.slice(0, stringJoined.lastIndexOf(','));
   let secondPart = stringJoined.slice(stringJoined.lastIndexOf(',')+1, stringJoined.length);
   stringJoined = firstPart + secondPart;
}
 
console.log(stringJoined);  // "JavaScript, TypeScript and React"

To make it resuable, create a utility function:

/* A utility function to convert array elements to a readable list */

function arrayToList (array) {
  if (array.length > 1) {
     array[array.length-1] = "and " + array[array.length-1];
  }

  let stringJoined = array.join(', ');

  if (array.length > 1) {
     let firstPart = stringJoined.slice(0, stringJoined.lastIndexOf(','));
     let secondPart = stringJoined.slice(stringJoined.lastIndexOf(',')+1, stringJoined.length);
     stringJoined = firstPart + secondPart;
  }  
  
  return stringJoined;
}

let myArray = ["JavaScript", "TypeScript", "React"];

arrayToList(myArray);