JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops For Loops

Dan Sutherland
Dan Sutherland
1,457 Points

Is the variable becoming an array?

In this example

var html = '';

for ( var i = 1; i <= 10; i += 1 ) {
html += '<div>' + i + '</div>';

document.write (html);

Is the loop storing a new iteration in the variable html every time it fires, and then when the loop breaks out i.e. when the counter reaches 10, then the document.write method writes the contents of html...which by this point holds an array of inputs as the loop has been round 10 times? Or have I got this totally wrong?

Is it instead that the loop goes through one complete cycle which includes ending with whatever is outside of the end curly brace THEN goes back to the start i.e. prints a new entry to var html every cycle?

Thanks Dan

1 Answer

54,281 Points

The loop executes the code in between the curly braces 10 times to build the following string: