Need Help With DOM Modification

Hello, I was hoping someone could help me understand the following example.

Write a function createTree that creates a nested ul/li list from the nested object.

let data = {
  "Fish": {
    "trout": {},
    "salmon": {}
  },
  "Tree": {
    "Huge": {
      "sequoia": {},
      "oak": {}
    },
    "Flowering": {
      "apple tree": {},
      "magnolia": {}
    }
  }
};

The solution:

let container = document.getElementById('container');

function createTree(container, obj) {
   container.innerHTML = createTreeText(obj);
}

function createTreeText(obj) { // standalone recursive function
  let li = '';
  let ul;

  for (let key in obj) {
    li += '<li>' + key + createTreeText(obj[key]) + '</li>'; (*)
  }

  if (li) {
    ul = '<ul>' + li + '</ul>' (**)
  }

  return ul || ''; (***)
}

createTree(container, data);

I was just wondering, do all the recursive calls in line (*) fill the call stack and reach the base case before moving on to the if statement in line (**), or does each iteration of the recursive call run all the way through to the return statement?

What would be the base case for the recursive call? If there is no base case, wouldn’t it keep creating nested <li> elements for infinity and beyond? Is the base case when there are no more key properties in the nested object?

The return ul || "" statement in line (***) is throwing me off. I changed the line to return ul and the code ran just fine. I do not understand the purpose of || "". What would be the purpose of returning an empty string when ul is undefined?

The way I sorta understand it is, the recursive call creates one massive list of nested <li> elements until it reaches the base case of there being no more key properties, and then it appends that entire tree one time to a single <ul> element.

Any clarification would be very helpful. Thank you!

hello, here is my take on this,

  • synchronous code flows from top to down fashion, which means if theres a “loop/check/function/etc” they’ll be executed before reaching eof
  • i suppose so, if that helps consider or probably more fitting, that function as a “reusable” function
  • this is also interesting to me as well, as i cant tell reason for it, but i suppose, its due to that fact how its being used in “createTree”, as innerHTML expects something to be added, perhaps for that reason maybe
  • sounds good to me :slight_smile:

hope this was helpful, happy learning :slight_smile:

1 Like

@bappyasif Thank you for your helpful input.

1 Like

glad i could help :slight_smile: as always, happy learning :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.