Cyclic Sequence Pattern

Understanding Cyclic Sequence Patterns in JavaScript

When working with arrays, there are times when you might want to iterate over the elements more than once in a cyclic manner. This means that after reaching the last element of the array, the iteration starts again from the first element. This can be easily achieved using the modulus operator (%). Let's explore how this can be done.

Example: Iterating Over Meals

Consider the following array of meal names:

let arr = ["breakfast", "lunch", "dinner"]

If we want to iterate through this array in a cyclic pattern, such that after the last item "dinner" we go back to "breakfast", we can use a for loop. Here's how it looks:

let arr = ["breakfast", "lunch", "dinner"];

for (let i = 0; i < 4; i++) {
    console.log(arr[i % arr.length]);
}

Explanation

In the example above:

  • The length of the array arr is 3.

  • The for loop runs from i = 0 to i < 4, which means it will iterate 4 times.

  • Within the loop, i % arr.length calculates the index to access the array elements. The modulus operator ensures that the index wraps around when i exceeds the array length.

    • When i = 0, 0 % 3 is 0, so arr[0] is "breakfast".

    • When i = 1, 1 % 3 is 1, so arr[1] is "lunch".

    • When i = 2, 2 % 3 is 2, so arr[2] is "dinner".

    • When i = 3, 3 % 3 is 0, so arr[0] is "breakfast" again.

Output

breakfast
lunch
dinner
breakfast

It is a concept I never knew of and will definitely be using more in the future. Wrote with the help of Chat GPT cause i was feeling quite lazy and procrastinated way too long to edit and publish it.

Happy coding!