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 trialGerald Bishop
Python Development Techdegree Graduate 16,897 PointsShould jQuery be able to use global variables?
If I declare the variable outside the click event handler then the append() method ignores the variable and only inserts the <li> tags.
Once the const variable declaration is cut and copied into the click event handler, then the code works as expected.
Shouldn't it work either way?
Thanks
1 Answer
Steven Parker
231,269 PointsThe variable itself is available either way, but what it contains is a matter of timing.
If the assignment is done at the global level, it is performed as soon as the page loads. Since the user has not had time to input anything yet, the value will be empty.
But inside the event handler, the code only runs after the user puts something into the input and clicks on the button.
Gerald Bishop
Python Development Techdegree Graduate 16,897 PointsGerald Bishop
Python Development Techdegree Graduate 16,897 PointsThanks for clearly explaining it. That makes perfect sense.