Search code examples
javascriptrecursionreturnnested-object

Why does recursion only result in the values of first nested object values and not the rest, when used return?


I used the return keyword when looping through the 'object' Object first recursively with the code below, but it only resulted in the king property's objects by looping a number of times, and when it reached sika property and value, it ended looping.

let object = {king: {lisa: {biza: {sika: 21}}}, queen:{billy: {silly: 23}}, guard: {son: 4}};

function goThrough(obj) {
  let list = Object.keys(obj);

  for(let keys of list) {
    console.log("property: " + keys + ", value: " + JSON.stringify(obj[keys]));
    goThrough(obj[keys]); //Note: using return keyword here results in only king's values looped over
  }  
}

goThrough(object);

but when I omitted return, it looped through the rest of the objects and their property value pairs. Can someone please explain why it ends with only the first objects values when return is used?


Solution

  • In order to easier comprehend the in loop recursion, put a return after goThrough() inside the loop.

    let object = {king: {lisa: {biza: {sika: 21}}}, queen:{billy: {silly: 23}}, guard: {son: 4}};
    
    function goThrough(obj) {
      let list = Object.keys(obj);
    
      for(let keys of list) {
        console.log("property: " + keys + ", value: " + obj[keys]);
        goThrough(obj[keys]);
        return;
      } 
    
    }
    
    console.log(goThrough(object))
    

    When using return as shown above, once the code comes back from the recursion it will stop the function execution immediately and will not go through other properties queen and guard. You explicitly disallow that by using return.

    If you omit the return, after having you first branch done king: {lisa: {biza: {sika: 21}}}, the code will continue with other properties and go as deep as it has to. The same thing which occurred for the first property king, it went down to all of its children (tnx to recursion).

    To understand it more. Put breakpoints inside your code and observe the stack calls, filling with functions and returning from them. Also you may put a console in between goThrough() and return and analyze the output.