Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))
In JavaScript, a variable can be defined, but hold the value undefined
, so the most common answer is not technically correct, and instead performs 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 may suffice for your purposes. The following test has simpler semantics, which makes it easier to precisely describe your code's behavior and understand it yourself (if you care about such things):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
This, of course, assumes you are running in a browser (where window
is a name for the global object). But if you're mucking around with globals like this you're probably in a browser. Subjectively, using 'name' in window
is stylistically consistent with using window.name
to refer to globals. Accessing globals as properties of window
rather than as variables allows you to minimize the number of undeclared variables you reference in your code (for the benefit of linting), and avoids the possibility 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.