Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript check if variable exists (is defined/initialized)

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) { 
like image 563
Samuel Liew Avatar asked Feb 25 '11 03:02

Samuel Liew


People also ask

How do you check if a variable has been initialized JavaScript?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check variable is defined or not?

The typeof operator will check whether a variable is defined or not. The typeof operator doesn't throw a ReferenceError exception when it is used with an undeclared variable. The typeof null will return an object. So, check for null also.

How do you check function is defined or not in JavaScript?

Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error.


2 Answers

You want the typeof operator. Specifically:

if (typeof variable !== 'undefined') {     // the variable is defined } 
like image 137
Jim Puls Avatar answered Sep 29 '22 13:09

Jim Puls


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 } 

For more info on using strict comparison === instead of simple equality ==, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

like image 28
Samuel Liew Avatar answered Sep 29 '22 12:09

Samuel Liew