Refactor a Loop in JavaScript to Use Recursion

Share this video with your friends

Send Tweet

Recursion is when a function calls itself. This self calling function handles at least two cases, the recursive case and the base case. People seem to either love it or hate it because it can be difficult to understand and implement correctly. Let’s walk through a recursive function and refactor a loop to instead perform the same result with a recursive function.

Dr.Emmett Brown
Dr.Emmett Brown
~ 6 years ago

Thank you for this useful course. I really would like to know that which IDE you've used in this course materials?

Stanislav
Stanislav
~ 6 years ago

Hi Tyler, thanks for the course.

Just a FYI: I've been playing around with the final code of this lesson and figured out that final function doesn't work for all arrays. e.g. findSix for const items =[[1,2,3],[4,5,[6],[9]]] will return no because hasSix variable will be overridden in consecutive iteration. Don't know if it's the most efficient way, but I merely put if (hasSix === 'yes') return; in the beginning of forEach loop to prevent it from overriding.

Stanislav
Stanislav
~ 6 years ago

@Dr.Emmett it's VS Code. The extension that shows results of console.log right in the editor window is Quokka.js.

Manjunath
Manjunath
~ 6 years ago

''' const somewhere = [6,6,undefined,131212312, 123,123 , 132, '', null, [[8]]];

function findNumber(num, arr) { if(arr === num) return true; if(!arr || !Array.isArray(arr)) return false; for(let i=0; i < arr.length; i++) { if(arr[i] === num) return true; if(Array.isArray(arr[i])) isFound = findNumber(num, arr[i]); } return false; } console.time('test1'); console.log(findNumber(6, somewhere)); console.timeEnd('test1'); '''

Manjunath
Manjunath
~ 6 years ago

Can someone please delete this and the above comment ?!. Thank you.

Tyler Clark
Tyler Clark(instructor)
~ 6 years ago

Good catch @Stanislav, that is a good way of doing it!

Tyler Clark
Tyler Clark(instructor)
~ 6 years ago

Thank you for this useful course. I really would like to know that which IDE you've used in this course materials?

I am using the pro version of https://quokkajs.com/

~ 6 years ago

Thank you Tyler, it is wonderful course, I learn a lot

~ 6 years ago

Thank you Tyler, it is wonderful course, I learn a lot

~ 6 years ago

Hi,Tyler, if I have const items = [[1, 2, 3],[4, 5,[6]],7,[8,9],[10,6]], how can I find all of 6 ?

~ 6 years ago

Hi,Tyler, if I have const items = [[1, 2, 3],[4, 5,[6]],7,[8,9],[10,6]], how can I find all of 6 ?

techtrainingAtshaadi
techtrainingAtshaadi
~ 5 years ago

Adding a 6 in the first array wouldn't work (I think the recursive case wasn't properly handled). So I had to modify the code to this:

const items = [[1, 2, 3, [6]], [4, 5, 5]];

function findSix(i) {
  let hasSix = 'no!';
  i.forEach(a => {
    if (hasSix === 'yes!') return;

    if (a === 6) {
      hasSix = 'yes!';
    }

    if (Array.isArray(a)) {
      hasSix = findSix(a);
    }
  });
  return hasSix;
}

console.log(findSix(items)); //=> true

https://codesandbox.io/s/recursive-findsix-lo9tb

techtrainingAtshaadi
techtrainingAtshaadi
~ 5 years ago

In a functional style (while returning a boolean), I would do this:

//recursive flatten deep
function flatten(array) {
  let flattend = [];
  !(function flat(array) {
    array.forEach(function(el) {
      if (Array.isArray(el)) flat(el);
      else flattend.push(el);
    });
  })(array);
  return flattend;
}

const findSix = arr => flatten(arr).some(equals(6));

The poinfree version with ramda and crocks would look like this:

const findSix = composeB(any(equals(6)), flatten);
Bojan
Bojan
~ 5 years ago

The video example is missing the base case of hasSix === yes!. Otherwise great tutorial