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 DOM Scripting By Example Adding and Removing Names Registering Names

const variables question

why are the const variables inside the event handler and not at the top?

2 Answers

Because you do not need to use those const variables anywhere else in the app, only the event handler needs those variables so they can be declared inside the handler.

Hey Jack Dolitsky,

Ella Ruokokoski is right. We don't declare them at the top since we don't need to access them globally. In addition, declaring them in the function makes sure that we don't accidentally access them elsewhere in the file. Lastly, declaring the variables only in the function means that we can reuse that variable name elsewhere if needed. For example, if we have another function that uses a text input value, we can use the variable name 'text' in that function.

Hope that makes sense. Happy coding!