JavaScript checking whether a variable exists
Submitted by dmartin on Fri, 11/09/2007 - 3:38pm
JavaScript provides no good way to check if a variable exists. If you try to use one that doesn't, you get a big fat error. I've seen some people use:
if (myVar == undefined)
But this only works if the variable has been declared, but wasn't set to a value. Sometimes, you don't know if the variable was even declared.
Here's some code that solves that:
try {
if (myVar) {}
} catch (err) {
var myVar = "";
}
You can do whatever you want in the catch block. Initializing the variable, as I show, is a good way to avoid errors you would've gotten if the variable didn't exist.
- dmartin's blog
- Add new comment
- 1705 reads
Weblog
Lil bit late, but in global