JavaScript JavaScript and the DOM 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,635 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
Tobiasz Gala
Full Stack JavaScript Techdegree Student 21,096 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' ....???