Quote:
Originally Posted by goofyballer
First one = `var j = i` first, log j?
Second one...
Code:
function traverse(element, callback) {
// assume children are in array element.children...?
// precondition: if no children, array exists and is empty
callback(element)
element.children.forEach(child => traverse(child, callback))
}
? I assume I'm missing something, not sure what the tricky part is.
That is why the first one is tricky. That doesn't work. That was my first inclination as well but it's wrong.
The second one is mostly right. I was told not to assume that there are any children so you would need to add a check around that then make the next recursive call.
inside the loop is the equivalent of
Quote:
var j [outside the loop]
j = i [inside the loop]
What that means is, by the time the first console.log runs, j/i has already been incremented to 4 so that gets console logged out 4 times.