Thursday, 12 September 2013

Check for undefined javascript variable?

Check for undefined javascript variable?

I am trying to check if a variable is defined, if it is then an ajax
request is run...If it is not I want the user to be redirected to a
separate page where the variable is set.
for example I want something like this:
// if variable is undefined
if (typeof accessKey === 'undefined') {
alert('the variable is not set!');
} else {
var accessKey = 'some random string generated from google';
alert('the variable is set!');
proceed to refresh the page and run through check again.
}
So the first time the page is run, it checks if the variable is set. If
the variable is not set it will set the variable and then reload the page
and run through the check again.
Problem is 'accessKey' always returns undefined but the code runs through
as if the variable is defined. Why?

No comments:

Post a Comment