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!