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

Problem with global variable scope in javscript

I have a global variable named professionIdentifier="null". I have an html document, HTML1.html that has an on click event to call a function showDistricts(professionIdentifier). In this function, i change the value of my previously initialized global variable professionIdentifier to 'carp'. So when I click the button in HTML1.html, the value of the variable changes. Now, I have a second html document, HTML2.html, that has a different on click event that calls a function named showNames() to alert to me the new value of professionIdentifier.

Now my problem is that the value that I get is 'null'. Why am I not receiving the new value of professionIdentifier which is supposed to be 'carp'.

Thank You Yousef

Have you checked that you're not redeclaring the professionalIdentifier variable in the showNames() function and therefore over-riding the global variable?

Yea, nothing is in the showNames() function except alert(professionIdentifier);

It might be to do with the fact that you're trying to access the global variable from two different pages then.

I'm fairly new to JS but I have a vague recollection that global variables are scoped to the page. If you want to access them from two different pages you might be able to use localStorage.getItem() and localStorage.setItem() to set and retrieve the value.

Yea I probably will have to use one of them in the end. Thanks anyways!

1 Answer

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Andy Bargh has the right answer here. A variable you set on one page does not persist to another page without additional programming. You can save the value as a cookie, then load it into the variable on the second page; use localstorage; place the variable in the URL (this would involve some on-the-fly re-writing of link clicks; or a backend database solution using a backend setup like Ruby on Rails, PHP, etc.