Reputation: 7734
I'm trying to do this:
var currentpage = page ? page : null;
However, if page is not yet defined, the script throws an error. Even if I test page for being undefined, as soon as the script looks up page it errors.
Why and what's the way around this issue?
Update : Made the code-example clearer;
Upvotes: 0
Views: 98
Reputation: 4617
Another way around would be like this, Even if your var a
is undefined the else will be executed, that is your script won't stop execution
if(window.a){
alert('hello');
} else {
alert('this else will fire');
}
Upvotes: 0
Reputation: 16905
Trying to read from an undeclared variable simply throws a ReferenceError
and terminates the script.
> x123
ReferenceError: x123 is not defined
The better question is, why you don't know whether your variable exists. Under normal circumstances, this usually implies you're doing something bad. Why is it that you need to check for that situation? Surely, there is a better way that we could suggest.
Upvotes: 1
Reputation: 521995
You must have defined the variable somewhere using var page
or as a function argument function (page)
. If you did this anywhere within the same scope, the variable is declared and exist, even if it has no value. If you're trying to work with some variable that is not even declared in the same scope, that's simply wrong because it cannot work under any circumstance and Javascript is entirely correct to throw an error.
Upvotes: 1
Reputation: 50563
Use typeof
operator for that:
var a = (typeof page != 'undefined') ? 'page=' + page: '';
alert(a);
Upvotes: 1