Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check if a Javascript variable exists?

Status
Not open for further replies.

omega113

Programmer
Jun 10, 2008
4
IN
Is there a way to check if a javascript variable exists?

I have multiple javascript files in my application.

I would like to check if a varible called __JSON has been used by any other file.

Any help would be appreciated

 
this does not work if you set

var __JSON = whatever


it does not pop up the alert box sayin
alert('It has been used before');


ive tried everything to get this type of script to work
 
I had similar problem and in my case I had to use slightly different syntax

if (typeof _JASON !="undefined")

In other words, I removed parens and suddenly it started to work. It gave me the same error variable is not defined when I tried to use it as typeof(Page_Validators).
 
Code:
<script type="text/javascript">
var __JSON = yes

if (typeof __JSON != 'undefined') {
   alert('It has been used before');
} else {
   alert('It has not been used before');
}

</script>
 
One of you is using two underscores to preceed the var and the other is not. You decide which.

David.
 
Code:
<script type="text/javascript">
var __JSON = "yes"

if (typeof __JSON != 'undefined') {
   alert('It has been used before');
} else {
   alert('It has not been used before');
}

</script>

i got it all working like so ^^^
variable has to be in quotes
 
It's probably breaking because 'yes' is undefined, and so a JS error is being thrown, stopping further processing:

Code:
var __JSON = yes;

A while ago, support for a pre-defined 'undefined' constant ('undefined') was added to JS, so you could instead write:

Code:
var __JSON = undefined;

It should have the same effect, although why do you need to define the variable at all?... the 'typeof' test should work regardless, I'd have thought.

Hope this helps,
Dan




Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top