Detecting existance of a variable

F

Fabian

How can I check whether or not a variable exists in a script? I'm
thinking in terms of

if (my variable exists) { myfunction(); }
 
R

Richard Cornford

Fabian said:
How can I check whether or not a variable exists in a script? I'm
thinking in terms of

if (my variable exists) { myfunction(); }

if(typeof x != 'undefined'){
...
}

Is as near as you can get. But a variable that is declared but has not
yet been assigned a value will also return 'undefined' from a typeof
test. A declared variable could be said to "exist" but in reality this
is probably suitable to your problem.

Richard.
 
K

KC Wong

How can I check whether or not a variable exists in a script? I'm
thinking in terms of

if (my variable exists) { myfunction(); }

It's an ugly hack, but you can use a try...catch block to do it.

try {
var i = myVariable;
// My variable is there...
myFunction();
} catch (exception) {
// My variable is not there
}


HTH,

KC
 
F

Fabian

Richard Cornford hu kiteb:
if(typeof x != 'undefined'){
...
}

Is as near as you can get. But a variable that is declared but has not
yet been assigned a value will also return 'undefined' from a typeof
test. A declared variable could be said to "exist" but in reality this
is probably suitable to your problem.

Thanks. That did the job. I have a javascript page separated into two
files, a data file and a parser file. By checking for the existance of
the variable, it can continue to handle the older version of the data
file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top