javascript

Looping without loops.

As a coder or an aspiring one you have probably experienced many moments where all the smokes blows away and you understand something much clearer. One of these moments for me was when I was introduced to recursion. Probably, while learning Scheme or Haskell. The basic idea is that a function calls itself. Don’t use recursion when you write definitions, because circularity is BAD philosophy so there comes the idea of writing Looping without loops.

Here is a very simple example that loops over an array, and prints the result, without using a regular loop; like while, for, do, map, forEach etc.

let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
function rec(arr){
  console.log(arr[0])
  if(arr.length > 1) rec(arr.slice(1))
}
rec(myArray);

You could of course do the same with a for of for example:

let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for(let val of myArray){
  console.log(val)
}

To figure out how to do something, without using the “default” is always a very good exercise. The basic idea above is to print the first element, and re-run the function if, the input is larger than one with the array minus the first element as input.

Leave a Reply