There are things we read when first learning a new programming language, but then we rarely have reason to use it in our day-to-day work shipping basic web apps.
One of those for me is the modulus (or remainder) operator.
In JavaScript, it's represented by the percent sign %.
I was building a video player with a preset playlist, and I wanted to loop back to the start of the playlist when reaching the end.
This was a simple use case for the modulus operator:
playNextVideo() {
const currentIndex = this.videos.indexOf(this.currentVideoId);
const nextIndex = (currentIndex + 1) % this.videos.length;
this.playVideo(this.videos[nextIndex]);
}
Take a look at the second line. Here is where we "loop" around back to the beginning of the playlist.
Because currentIndex is zero-based, when we increment it, and the new values equals our playlist length, the modulus operator returns 0, wrapping us around to the start of the array.
Here to help,
Joel
P.S. Want to hire us to build one of those basic CRUD apps? We are quite proficient at it! And we're good at the complex stuff too 😉