Exercise 10 Loops
Exercise 10 Loops
<!DOCTYPE HTML>
<html>
<body onload="demoLoop()">
<p id="resultPar"></p>
<script>
function demoLoop() {
var result = "";
for (var i = 0; i < 10; i++) {
result += "<p>" + i + "</p>";
}
resultPar.innerHTML = result;
}
</script>
</body>
</html>
The demoLoop function has a variable called result, which starts out as an empty string. Every time in
the loop, it adds the value of variable i between two paragraph tags. When the loop is over, there will be
10 paragraph tags, which become the html for the resultPar paragraph.
Save this as loops.html. Open it in your browser, and you should see the numbers 0 through 9.
Count by twos
Now modify the for loop so that instead of adding one each time, it adds two. Hint: use the += shortcut.
Save and refresh the page. Note that the total number of paragraphs is lower. That is because the
conditional is still going to make the loop stop when i < 10.