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 and the DOM (Retiring) Getting a Handle on the DOM A Simple Example

Since we cant access the 'const' outside its scope, how come we add it to Eventlistener and Style.?

Since we cant access the 'const' outside its scope, how come we add it to Eventlistener and Style.?

3 Answers

Neil McPartlin
Neil McPartlin
14,662 Points

In the video we see that on line 1 of the app.js, Guil has declared a 'const' in the global scope which means it can be used both outside and within functions as shown, but you are wise to be wary of scopes.

There is another Treehouse video you may have seen which warns about the dangers of functions using variables declared in the global scope, as the function might change the variable content which could have unintended consequences for other parts of the code.

For this reason, it is good practice to declare variables, needed by a function, within the function i.e. within that function's scope. These variables can only be 'seen' within the function and not outside.

Tobiasz Gala
seal-mask
.a{fill-rule:evenodd;}techdegree
Tobiasz Gala
Full Stack JavaScript Techdegree Student 23,529 Points

Because programming is not something that could be done just in one way. You could use let which is perfectly fine, however, let allows you to modify this variable. Const make sure that you cannot reassign this variable and it always will provide a reference to myHeading element.

I second John. If u say that "Guil has declared a 'const' in the global scope which means it can be used both outside and within functions as shown", then why dont we just use 'let' ....???