[javascript] 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")....

This question is related to javascript jquery variables

The answer is


For your case, and 99.9% of all others elclanrs answer is correct.

But because undefined is a valid value, if someone were to test for an uninitialized variable

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way


Before each of your conditional statements, you could do something like this:

var pagetype = pagetype || false;
if (pagetype === 'something') {
    //do stuff
}

You can use typeof:

if (typeof pagetype === 'undefined') {
    // pagetype doesn't exist
}

To test for existence there are two methods.

a. "property" in object

This method checks the prototype chain for existence of the property.

b. object.hasOwnProperty( "property" )

This method does not go up the prototype chain to check existence of the property, it must exist in the object you are calling the method on.

var x; // variable declared in global scope and now exists

"x" in window; // true
window.hasOwnProperty( "x" ); //true

If we were testing using the following expression then it would return false

typeof x !== 'undefined'; // false

It is impossible to determine whether a variable has been declared or not other than using try..catch to cause an error if it hasn't been declared. Test like:

if (typeof varName == 'undefined') 

do not tell you if varName is a variable in scope, only that testing with typeof returned undefined. e.g.

var foo;
typeof foo == 'undefined'; // true
typeof bar == 'undefined'; // true

In the above, you can't tell that foo was declared but bar wasn't. You can test for global variables using in:

var global = this;
...
'bar' in global;  // false

But the global object is the only variable object* you can access, you can't access the variable object of any other execution context.

The solution is to always declare variables in an appropriate context.

  • The global object isn't really a variable object, it just has properties that match global variables and provide access to them so it just appears to be one.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?