I am working on a solution for the "looping a triangle" exercise at the end of Eloquent JavaScript ch2. The book asks to log output to the console but I want to print the output to a webpage instead, in a div with id="triangle".
This code is printing the right number of hashes. The problem is that the
tag that is created within the for loop is mysteriously removed when the loop increments in the final expression. That is: if I step through the code hashPrint.appendChild(carriage) executes fine at the breakpoint, but once the debugger gets to i++ the
child element is removed from the web page.
var hash = "";
var hashPrint = document.getElementById("triangle");
var carriage = document.createElement("br");
for (var i = 0; i < 7; i++) {
hash += "#";
var content = document.createTextNode(hash);
hashPrint.appendChild(content);
hashPrint.appendChild(carriage);
}
If I put the var carriage declaration within the for loop it works fine. I know that JS best practice encourages avoiding global scope, I've been doing a lot of Java programming lately and it seemed to me that having the createElement("br") in global might be handy if I want to use it in another loop on the page.
Even though I already have a solution for the issue, I'd like to know why the final expression on the for loop would trigger the removal of the child node. Basically, why doesn't this work? I have searched high and low for an explanation with no luck.