How to show images from an array using JavaScript - The Easy Way

← PrevNext →

There are few simple methods in JavaScript that you can use to extract images from an array and display it. The method that I am going to share in this article uses the .map() function.

The array.map() function creates an array from another array (the original array). We can use the map() function to create an array of <img /> tags and then show the images on our web page by placing the tags in a DIV element.

➡️ Learn more about ES6 map() function

The markup and the script
<div id="container"></div>   <!--   show images here. -->

<script>
  const arr = ['../../images/theme/css.png', 
               '../../images/theme/angularjs.png',
              '../../images/theme/javascript.png'];

  const img = arr.map(img => `<img src="${img}" />`);
  container.innerHTML = img.join('<br />');
</script>
Try it

The map() function iterates or loops through an array using a callback function (or the mapping function). See the syntax. Each element is sent to the callback function, which then returns a new element, and the map() creates a new array using the returned elements.

← PreviousNext →