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 Working with 'for' Loops Dynamically Display HTML with a Loop

changing html outside of the loop

How is the program html-loop.js able to access the html value outside of the loop itself?

const main = document.querySelector('main');

let html = '';

for ( let i = 1; i <= 100; i++ ) { html += <div>${i} </div>; }

main.innerHTML = html;

Javascript has 2 scopes when talking about functions reaching into other functions, but in this case we're reaching into and adding to the HTML from JS which has nothing to do with scope.

document = this web page querySelector = to select ( 'return' element) ('main') = element

innerHTML = to place content(HTML markup) inside of (which is why we're including <div></div> tags, because we're literally inserting what's stored in the variable of 'html' into the real HTML of the page.)

So the JS is saying:

On this webpage go and find 'main' in the HTML and insert into it the content we generated and stored in 'html' using the '.innerHTML' command. My terminology is I'm sure terrible here but I hope that helps you understand.

2 Answers

I can see how this would be confusing after having just completed the courses on functions.

To the best of my knowledge, which is admittedly limited, in Javascript there are only 2 levels of scope, global and local.

Functions create a local scope, but for loops do not.

Do bear in mind that even in the local scope of a function you still will always be able to access variables from within the parent( or global ) scope.

For more clarification I recommend reviewing this video: https://teamtreehouse.com/library/variable-scope-3

If your original question has been answered, you can mark the question solved by choosing a "best answer".

walter palma
walter palma
3,189 Points

Im not sure what you are asking here, but if the loop is in the same scope you can always access the value