Create an Array of Images in JavaScript (Tutorial)

The best ways to create and use arrays of images in JavaScript.

Published Categorized as JavaScript, Web & Code

In JavaScript, as in other programming languages, arrays are objects that allow you to store more than one data item under a single variable name.

Each data item you store in an array is assigned a unique index—a number that indicates where exactly in the array that data item is stored, if you will—starting with 0 (the first item has an index of 0, the second an index of 1, the third and index of 3, and so on).

Once you’ve stored the data items in your array, you can then use JavaScript’s vast library of methods to work with them. For example, you can find and filter values in an array, join the items in an array and turn them into a string, concatenate two arrays together, and many, many others.

With a little imagination and ingenuity, you can also create “arrays of images” for all kinds of use cases on the frontend.

How Arrays of Images Work

You can’t store image files in JavaScript. So your array of images would actually be an array of references to images hosted elsewhere.

Simple Array of Images

The simplest, most straightforward way to create an array of images is to declare an array object and push the URLs to your images to it.

// Declare an array object for our array of images
let arrayOfImages = [];

// Push the URLs to three images to arrayOfImages
arrayOfImages.push('https://site.com/image-1.jpeg');
arrayOfImages.push('https://site.com/image-2.jpeg');
arrayOfImages.push('https://site.com/image-3.jpeg');

// Output arrayOfImages to the console
console.log(arrayOfImages);

You can try this out right now by opening your browser’s console, copy/pasting the above code to it, and hitting the “Enter” key on your keyboard.

If you do, you will observe the following outputs:

Pushing image URLs to arrayOfImages

Suppose you want to store more than just the URL to each image. You can create nested arrays that store arbitrary metadata such as the title, height, and width of the images.

// Declare an array object for our array of images
let arrayOfImages = [];

arrayOfImages.push(['https://site.com/image-1.jpeg','Title 1','768px','1024px']);
arrayOfImages.push(['https://site.com/image-2.jpeg','Title 2','720px','1280px']);
arrayOfImages.push(['https://site.com/image-3.jpeg','Title 3','1080px','1920px']);

// Output arrayOfImages to the console
console.log(arrayOfImages);

If you copy/pasted the above code into your browser’s console and ran it, you’d see a structured list of images in your arrayOfImages array object.

Pushing image URLs, titles, height, and width to arrayOfImages

As long as you always store the URLs in Index 0, the titles in Index 1, and height in Index 2, and the width in Index 3, you’re going to have an array of images that you can reference, mutate, and reassign as needed.

Array of Images With Image() Constructor

If you’re doing this for a frontend application and your end goal is to show these images on the screen, consider using JavaScript’s Image() constructor instead.

The syntax of the Image() constructor is limited only to the width and the height of your image:

// Create HTMLImageElement
let myImage = new Image(width, height);

You can then assign HTMLImageElement properties, like the src attribute, to it:

// Create HTMLImageElement
let myImage = new Image(width, height);

// Assign it an src attribute
myImage.src = 'https://site.com/example-1.jpeg';

Once you’ve created your image object, you can then push it to arrayOfImages as usual:

// Declare an array object for our array of images
let arrayOfImages = [];

// Create image object and assign width and height
let myImage = new Image('1024','768');
// Assign src attribute to image object
myImage.src = 'https://site.com/example-1.jpeg';

// Push image object to arrayOfImages
arrayOfImages.push(myImage);

// Output arrayOfImages to the console
console.log(arrayOfImages);

Every time you use the Image() constructor, you create a new instance of an HTMLImageElement. You can these reference and manipulate that HTMLImageElement as you wish.

Once you’ve created your image objects and stored them in an array, inserting them into your HTML document is as simple as using the method you need and referencing the right index:

// Append an <img> element to the <body> tag
document.body.appendChild(arrayOfImages[0]);

// Insert an <img> element as the inner HTML of div#image-01
document.querySelector('div#image-01').innerHTML(arrayOfImages[0]);

Things to Know

Pushing Images to the Array

There are two ways to push images to your array, and which one to use comes down to your implementation and requirements.

The easiest way to do this is with the Array.push() method, which adds one or multiple, comma-seprated, elements to the end of the array.

Once it is done, the Array.push() method returns the array’s new length:

// Declare an array object for our array of images
arrayOfImages = [];

// Push the URL of two images to arrayOfImages
arrayOfImages.push('https://site.com/image-1.jpeg', 'https://site.com/image-2.jpeg');

console.log(arrayOfImages);

For example, if you copy/pasted the above code into your browser’s console and executed it, this is what you would observe:

Pushing image URLs to the array using Array.push()

If you ought to store images in specific indices, or you want to overwrite the metadata for an image that’s already stored in your array, you can use the following method:

Array[index] = value;

Suppose we want to overwrite the URL of the second image from our example above with an updated one. Our code would then look like this:

// Declare an array object for our array of images
arrayOfImages = [];

// Push the URL of two images to arrayOfImages
arrayOfImages.push('https://site.com/image-1.jpeg', 'https://site.com/image-2.jpeg');

// Update the URL of the second image
arrayOfImages[1] = 'https://site.com/image-2-final.jpeg';

console.log(arrayOfImages);

Lo and behold, the second image’s URL is now updated:

Updating values of existing images using Array[index] = value

Cleaning Up the Array

You can delete individual items from the array. For example, the code below will “empty” index 1 of arrayOfImages:

// Delete index 1 of arrayOfImages
arrayOfImages[1] = '';

Or you can delete all elements from the array altogether by redeclaring it as an empty array:

// Redeclare arrayofImages as an empty array
arrayOfImages = '';

It’s important to note that you cannot redeclare or reassign a constant, so your array of images must be declared using the var statement (for function scope) or the let statement (for block scope) for you to be able to “reset” it.

Image courtesy of archideaphoto /Depositphotos

Leave a comment

Your email address will not be published. Required fields are marked *