Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,517 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' ....???