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.))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
Asked by Samuel Liew
Solution #1
The typeof operator is what you’re looking for. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
Answered by Jim Puls
Solution #2
The typeof operation will determine whether or not the variable is indeed undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
When used with an undeclared variable, the typeof operator, unlike the other operators, does not throw a ReferenceError exception.
It’s worth noting, though, that typeof null will return “object.” To prevent making the mistake of initializing a variable to null, we must be cautious. To be safe, we may use the following instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
See Which equals operator (== vs ===) should be used in JavaScript comparisons for further information on using strict comparison === instead of basic equality ==.
Answered by Samuel Liew
Solution #3
In many circumstances, it’s best to use:
if (elem) { // or !elem
will do the job for you! … this will check these below cases:
So that will cover almost all scenarios, but there will always be odd cases that we’d like to cover, such as a string with spaces, such as this” one, which will be defined in javascript because it has spaces inside the string… for example, in this case you add one more check using trim(), like:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Also, because objects and arrays function differently in Javascript, these checks are only for values; empty array [] and empty object are always true.
To give you a short overview of the answer, I created the graphic below:
Answered by Alireza
Solution #4
Because a variable in JavaScript can be defined but its value left undefined, the most typical answer isn’t technically right, and instead does the following:
if (typeof v === "undefined") {
// no variable "v" is defined in the current scope
// *or* some variable v exists and has been assigned the value undefined
} else {
// some variable (global or local) "v" is defined in the current scope
// *and* it contains a value other than undefined
}
That might be plenty for your needs. The following test has clearer semantics, making it easier to properly define and understand your code’s behavior (assuming you care about that):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
Of course, this presupposes you’re using a browser (where window is a name for the global object). You’re presumably in a browser if you’re messing about with globals like this. Subjectively, using ‘name’ in window is stylistically congruent with referring to globals using window.name. Accessing globals as window properties rather than variables reduces the amount of undeclared variables in your code (for linting purposes) and eliminates the danger of your global being shadowed by a local variable. Also, if globals make your skin crawl you might feel more comfortable touching them only with this relatively long stick.
Answered by Brian Kelley
Solution #5
In the vast majority of circumstances, you’d say:
elem != null
Unlike a simple if (elem), it allows 0, false, NaN and ”, but rejects null or undefined, making it a good, general test for the presence of an argument, or property of an object.
The other checks aren’t bad either; they just have different applications:
A strict comparison against undefined is also useful:
if (elem === undefined) ...
Because the global undefined variable can be overridden by another value, it’s recommended to declare the variable undefined in the current scope first:
var undefined; // really undefined
if (elem === undefined) ...
Or:
(function (undefined) {
if (elem === undefined) ...
})();
A secondary advantage of this method is that JS minifiers can reduce the undefined variable to a single character, saving you a few bytes every time.
Answered by David Tang
Post is based on https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized