This simple math hack lets you create an image carousel without any if statements
Tags: math, cs, javascript, webdev
Published: 2019-09-25 01:52:06

---
title: This simple math hack lets you create an image carousel without any if statements
published: true
description: Stop writing complicated if/else statements for your image carousels. This tutorial shows you how to move through your images with one line of code.
tags: math, cs, javascript, web development
cover_image: https://thepracticaldev.s3.amazonaws.com/i/a1mx7pochnxyfx2bw2ey.jpg
---

If you are a web developer or a web developer student, you have probably made at least one image carousel in your career. In fact, you've probably made a few. While there are plenty of image carousel libraries out there, sometimes you want (or need) to make it from scratch. 

Most image carousels are made from arrays of image data. When some event triggers a change (a timeout, button click, etc) the current image data is replaced with the next element in the array. The tricky part for many comes when they reach the end of the array. Now what? If you've been writing complex if statements trying to check for this condition, I'm here to tell you there's a better way.

Observe the code below:
```javascript
const imageData = [ 'image1.png', 'img2.png', 'img3.png' ];
let currentImage = 0;

const handleImageChange = () => {
  currentImage = (currentImage + 1) % imageData.length;
}
```

That's it. That's the whole thing. (Explanation below amazed Keanu.)

![Keanu Reeves looking dumbfounded, or maybe just dumb](https://thepracticaldev.s3.amazonaws.com/i/qnhnybjm1e9ktzmg2zpr.jpg)

## How it works

Let's assume we have an array of 10 elements. Modulo division (what happens when you use the `%` operator) returns the remainder of the division. If `currentImage` is 0, then `(0 + 1) % 10` is the remainder of `1/10`, which is 1. This is because we cannot actually divide 1 by 10, so the whole dang 1 is left over. The same is true of 2 - 9. None of these numbers can be divided by 10, so the number itself is the remainder. The magic happens when we get to 10. 

Since our array is zero-index, there is no tenth element. This works in our favor! When you divide a number by itself, the remainder is 0, which means our `currentImage` will be set to 0. This means that as soon as we get past the end of our array, its going to go back to the beginning. Nifty, yeah?

In computer science, this is known as a circular array. The array itself is just a plain ole array, but we use this math trick to allow it to loop indefinitely.

But, wait! What if we want to go the other way? Don't worry, I got you!

We can do the same thing in reverse. The formula for this is  `(currentValue - 1 + totalElements) % totalElements`. If we add this to the above example, it could look something like this.

```javascript
const imageData = [ 'image1.png', 'img2.png', 'img3.png' ];
const currentImage = 0;

const handleImageChange = (direction) => {
  if (direction == 'forward')
    currentImage = (currentImage + 1) % imageData.length;
  else
    currentImage = (currentImage - 1 + imageData.length) % imageData.length;
}
```

I know, I know, I said there wouldn't be any `if` statements, and there aren't, at least not for actually moving forward and back through the elements. We just need to know which direction to go.

This isn't just great for image carousels. Any time you need to increment through an array one element at a time, this will eliminate any condition checking to see if you are at the end. 

[Cover image by Michael and Sherry Martin (flickr)](https://www.flickr.com/photos/martinvirtualtours/2589290716/in/photolist-4WNMVo-8meden-4X98cR-npccaY-hMb4JG-CwyER-2auJs4-9fRWVK-evvmG4-9fS2bi-pDp7dm-5rhQu8-8sgGyD-78g8x9-5iRXxZ-98MPyx-3cos9k-dKVhfi-6KqcpM-7hEh3q-8cZX4X-6jPyNV-9MK7A5-7QphnS-dC2Ug7-zmh9j-aqH1Dv-duAefU-puJy5b-5CMBMj-RJTLLv-4mcRoX-2ctQi2a-e1CCBK-Qm7HEq-JEJbAP-KdTura-29Ayn7Y-j1mQi-C6Xc-2bRLJTV-bx2c3J-UpL74g-avkw7C-7QphV9-M5GUc-9fV5f9-98MPKH-2QABwu-7obWa)