How can I check whether a variable is defined in JavaScript?

Morgan Cheng picture Morgan Cheng · Feb 6, 2009 · Viewed 260.9k times · Source

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))

if (elem) { // or !elem

or

if (typeof(elem) !== 'undefined') {

or

if (elem != null) {

Answer