I fear not the man who has practiced 10,000 kicks once, but I fear the man who has practiced one kick 10,000 times.
One of my favorite programming exercises is to see how many different ways I can do one thing. I try to focus on something small because I usually do this exercise as a warm-up or when I’m sick of programming whatever I’m programming that day. I find that taking a step back to tinker with something small in scope is a great way to get some momentum and flow back into my programming. It’s a simple but rewarding exercise and I’m always surprised at the results.
Today, that something will be a task that I’m very familiar with: looping over an array.
After 10 years of programming in JavaScript, I honestly thought that I knew every single way to loop over an array. I was wrong, and I ended up learning some new tricks: the ES6 for-of loop, using pre-increment to write a concise while loop, and how to translate ML style recursion into JavaScript.
To get the most out of our time together, I challenge you to do the same exercise before looking at what I came up with. Full disclosure, my results have been revised and edited numerous times in order to make me look like a competent programmer. I originally came up with 11 ways but many of them were redundant I also spent an embarrassing amount of time working on the last one because my grasp of recursion has oxidized mildly.
1. For Loop
1for (let i = 0; i < array.length; i++) {
2 console.log(array[i]);
3}
2. For In Loop
1for (let i in array) {
2 console.log(array[i]);
3}
3. For Of Loop
1for (let item of array) {
2 console.log(item);
3}
4. While Loop
1let i = -1;
2while (++i < array.length) {
3 console.log(array[i]);
4}
5. Do While Loop
1let i = 0;
2do {
3 console.log(array[i]);
4} while (++i < array.length);
6. Array.forEach Method
1array.forEach((item) => {
2 console.log(item);
3});
7. ML Style Recursion
1let map = (f, [x, ...xs]) =>
2 x == undefined ?
3 [] :
4 [f(x), ...map(f, xs)];
5
6map(console.log, array);