Reputation: 2330
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:
if(folderName === folderArg.toLowerCase())
gets executed both via the console.log
statement and the data in the debuggerHowever, 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
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:
fib(1)
fib(2)
0 + 1
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