HelloWorld
HelloWorld

Reputation: 2330

Why isn't my recursive function returning the final result?

I have a method which traverses an nested object recursively until it finds a matching folder name:

findSpecifiedFolder(data) {
    const bookmarks = JSON.parse(data).roots.bookmark_bar.children;
    const search = bookmarks => {
        for(let folder of bookmarks) {
            const folderName = folder.name.toLowerCase();
            if(folderName === folderArg.toLowerCase()) {
                console.log(folder); // returns folder object
                return folder // never returns anything
            }
            else if(folder.children) {
                search(folder.children);
            }
        }
    };
    search(bookmarks);
}

So by using console.log and my debugger I can see the following:

  1. The method does, in fact recursively search the given object, nested at least 3 levels deep.
  2. I can confirm that I do in fact have a successful check when if(folderName === folderArg.toLowerCase()) gets executed both via the console.log statement and the data in the debugger

However, the return statement isn't getting executed (confirmed with debugger) and the method returns undefined (or an error when I called by another method with error logging). I no idea why so here I am asking if anyone might see some mistake in the method that I am missing.

Upvotes: 0

Views: 121

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

You have to return the recursive call, or else the returned value will not be delegated and returned when all recursive calls are resolved:

else if(folder.children) {
    return search(folder.children);
}

A simple proof of concept is the Fibonacci sequence. Here's some pseudocode (without return):

function fib(n) {
    if n is 1 return 0;
    else if n is 2 return 1;
    else fib(n - 1) + fib(n - 2);
}

So if I call fib(2), it will go through the following execution steps:

  1. Go to else
  2. Call fib(1)
  3. Return 0
  4. Call fib(2)
  5. Return 1
  6. Add 0 + 1
  7. Then do nothing. The code is basically else 1; which is an expression (the 1 part) and does nothing.

Since there is no return, the final result is computed, but you do nothing with it and the function returns undefined. You have to return it. The same principle applies here.

Upvotes: 2

Related Questions