One of the more significant changes when starting to code in a more functional way is that we get rid of for loops. Now that we know about recursion, we can just use that instead. Let's have look at a simple imperative piece of code that prints an array:
// demo of printing an array, imperative stylelet array = [1, 2, 3, 4, 5];function print(arr) { for(var i = 0, i < arr.length; i++) { console.log(arr[i]); }}print(arr);
The corresponding code using recursion looks like this:
// print.js, printing an array using recursionlet array = [1, 2, 3, 4, 5];function print(arr, pos, len) { if (pos < len) { console.log(arr[pos]); print(arr, pos + 1, len); } return;}print(array, 0, array.length);
As we can see, our imperative code is still ...