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
arris 3.The
forloop runs fromi = 0toi < 4, which means it will iterate 4 times.Within the loop,
i % arr.lengthcalculates the index to access the array elements. The modulus operator ensures that the index wraps around wheniexceeds the array length.When
i = 0,0 % 3is 0, soarr[0]is "breakfast".When
i = 1,1 % 3is 1, soarr[1]is "lunch".When
i = 2,2 % 3is 2, soarr[2]is "dinner".When
i = 3,3 % 3is 0, soarr[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!
