Possible Duplicate:
How can I check whether a variable is defined in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
I have a script that occurs in two parts.
The first part sets up a var:
var pagetype = "textpage";
The 2nd part is a simple if statement:
if(pagetype == "textpage") { //do something };
Now the 2nd part, the if statement, appears on all pages of my site. But the first part, where the var is declared, only appears on some of my pages.
On the pages without the var I naturally get this error:
Uncaught ReferenceError: pagetype is not defined
So my question is: is there a way with JavaScript or JQ to detect if a var exists at all (not just if it has data assigned to it)?
I am imagining I would just use another if statment, eg:
if ("a var called pagetypes exists")....
I suspect there are many answers like this on SO but here you go:
if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) { ... }
You can use typeof
:
if (typeof pagetype === 'undefined') { // pagetype doesn't exist }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With