Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery/Javascript: check if var exists [duplicate]

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").... 
like image 599
MeltingDog Avatar asked Dec 19 '12 01:12

MeltingDog


2 Answers

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

if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {   ... } 
like image 150
elclanrs Avatar answered Sep 16 '22 18:09

elclanrs


You can use typeof:

if (typeof pagetype === 'undefined') {     // pagetype doesn't exist } 
like image 33
Blender Avatar answered Sep 17 '22 18:09

Blender