Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

JavaScript check if variable exists (is defined/initialized)

Which technique for checking if a variable has been initialized is better/right? (Accepting the variable could hold anything (string, int, object, function, and so on))
if (elem) { // or !elem


or

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


or

if (elem != null) {
by

2 Answers

aashaykumar
You want the typeof operator. Specifically:

if (typeof variable !== 'undefined') {
// the variable is defined
}
sandhya6gczb
The typeof operator will check if the variable is really undefined.

if (typeof variable === 'undefined') {
// variable is undefined
}

The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}

Login / Signup to Answer the Question.