< Back

Document Subject: Javascript how to detect if a variable exists
Hint Short Cut: Add this to your code & documentation to help you find this page.
http://#javascriptdetect or http://A555F9/nn.nsf/ByAlias/javascriptdetect

How to check if a javascript variable exists before using it and causing an error.




You can use   http://notesninjas.com/#JSFieldExist to test to see if a field exists on a form, but sometimes you need to check to see if a variable exists.

 

Using

if (varname) alert("exists")

doesn't work.

You need to use typeof.

if (typeof(varname)!="undefined") alert("exists") else alert("doesnt exist')

you can also test for number string bookean object or null

 

 

 

From http://www.javascriptkit.com/javatutors/determinevar2.shtm