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

Dan Sutherland
Dan Sutherland
1,110 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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,939 Points

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

'<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div>7</div><div>8</div><div>9</div><div>10</div>'