patternjavascriptCritical
JavaScript check if variable exists (is defined/initialized)
Viewed 0 times
initializedcheckexistsdefinedvariablejavascript
Problem
Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))
or
or
(Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elemor
if (typeof elem !== 'undefined') {or
if (elem != null) {Solution
The
The
However, do note that
For more info on using strict comparison
Which equals operator (== vs ===) should be used in JavaScript comparisons?
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?
Code Snippets
if (typeof variable === 'undefined') {
// variable is undefined
}if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}Context
Stack Overflow Q#5113374, score: 1134
Revisions (0)
No revisions yet.