No more loops

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 style

let 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 recursion

let 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 there in spirit. We still start at 0. Moreover, we keep going until we come to the last position of our array. Once we hit our break condition, we exit the method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.70.254