Search code examples
javascriptjqueryvariables

JQuery/Javascript: check if var exists


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")....

Solution

  • I suspect there are many answers like this on SO but here you go:

    if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
      ...
    }