DEV Community

Discussion on: This simple math hack lets you create an image carousel without any if statements

Collapse
 
jeancarl profile image
JeanCarl

Once you figure out the modulus operator, it's a pretty cool operator! A ternary operator can get rid of that last if:

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

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

(also changed currentImage to let (otherwise "Assignment to constant variable." error)

Collapse
 
skhmt profile image
Mike

I wouldn't say a ternary is better than an if, especially for multi-line things like this.

Collapse
 
ranewallin profile image
Rane Wallin

Thanks. I fixed it. I do that all the time.