Are loops the only way to print an array?

I have the next array and I was wondering if a loop is the only way to print out my array, it is possible to do it in another way more easier?

function functieArray() {
    var gallery = document.getElementById("pozeGallery");
    for (i = 0; i < imgArray.length; i++) {
        gallery.appendChild(imgArray[i]);
    }
};
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '1.png';

imgArray[1] = new Image();
imgArray[1].src = '2.png';

imgArray[2] = new Image();
imgArray[2].src = '3.png';

Technically, and skipping parallelism for now, yes.

It all boils down to sequentially visiting each element of a list in order to print it whole. In assembly language you do it with a loop that stops either by knowing the length of the array in advance or stopping when the current element is equal to something that represents “nothing”; for example the null terminator \0

In JavaScript, the most primitive way is using a loop from 0 to the length of the array - 1. But there’s syntax sugar, functional iterative methods of the array prototype and even cheesy ways:

1- forEach

array.forEach(console.log)

This is part of the ES5 spec of JS that has a forEach method for arrays that does “something” (the function you pass to it) to each item in the list; but innerly, it performs a loop.

2- For of loop

for (let item of array) {
  console.log(item)
}

A special kind of loop introduced in ES6.

3- While loop

let i = 0
let len = array.length

while (i < len) {
  console.log(array[i])
  i++
}

4- By consoling out the whole thing ofc, why did we not think of that

console.table(array) // good for 2D arrays
// and pseudoarrays with named keys

console.log(array) // general overview
1 Like