Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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

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>'