Skip to content

JavaScript Print Array | Example code

  • by

There are 2 ways to print Array in JavaScript. First use The toString() method returns a string with array values separated by commas.

array.toString()

Or if need to print array elements, do loop over the array and print each element to the console.

for(let i = 0; i < arr.length; i++){
  console.log(arr[i]);
}

Examples Print Array in JavaScript

Simple example code Print Array all element in Single line.

  <!DOCTYPE html>
  <html>
  <head>

    <script>
      const fruits = ["Kiwi", "Orange", "Apple", "Mango"];
      let res = fruits.toString();

      console.log(res)
    </script>

  </head>
  </html>

Output: Banana,Orange,Apple,Mango

Example Print each array element.

<script>
      const fruits = ["Kiwi", "Orange", "Apple", "Mango"];
      
      for(let i = 0; i < fruits.length; i++){
        console.log(fruits[i]);
      }
</script>

Output:

JavaScript Print Array

If you want the elements to be printed on a web page. You can do so by assigning the array as the innerHTML property of an element.

<script>
      let arr = ["A", "B", "C"];
      document.getElementById("arrPrint").innerHTML = arr;
</script>

JSON format print Array

<script>
      let arr = [{name: "Jack"}, {name: "John"}, {name: "James"}];
      document.getElementById("arrPrint").innerHTML = JSON.stringify(arr, null, 2);
</script>

Output:

[
  {
    "name": "Jack"
  },
  {
    "name": "John"
  },
  {
    "name": "James"
  }
]

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading