An alternative to the plethora of typeof
answers;
Global variables declared with a var varname = value;
statement in the global scope
can be accessed as properties of the window object.
As such, the hasOwnProperty()
method, which
returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it)
can be used to determine whether
a var
of "varname" has been declared globally i.e. is a property of the window
.
// Globally established, therefore, properties of window
var foo = "whatever", // string
bar = false, // bool
baz; // undefined
// window.qux does not exist
console.log( [
window.hasOwnProperty( "foo" ), // true
window.hasOwnProperty( "bar" ), // true
window.hasOwnProperty( "baz" ), // true
window.hasOwnProperty( "qux" ) // false
] );
What's great about hasOwnProperty()
is that in calling it, we don't use a variable that might as yet be undeclared - which of course is half the problem in the first place.
Although not always the perfect or ideal solution, in certain circumstances, it's just the job!
Notes
The above is true when using var
to define a variable, as opposed to let
which:
declares a block scope local variable, optionally initializing it to a value.
is unlike the var
keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
At the top level of programs and functions, let
, unlike var
, does not create a property on the global object.
For completeness: const
constants are, by definition, not actually variable (although their content can be); more relevantly:
Global constants do not become properties of the window object, unlike var
variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared.
The value of a constant cannot change through reassignment, and it can't be redeclared.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Since let
variables or const
constants are never properties of any object which has inherited the hasOwnProperty()
method, it cannot be used to check for their existence.
Regarding the availability and use of hasOwnProperty()
:
Every object descended from Object inherits the hasOwnProperty()
method. [...] unlike the in
operator, this method does not check down the object's prototype chain.
foo
is declared, eithertypeof foo === 'undefined'
ortypeof foo === typeof undefined
– Italianateundefined
. The correct answer is this one: https://mcmap.net/q/40517/-javascript-check-if-variable-exists-is-defined-initialized – ErrolhasOwnProperty('bar')
doesn't have the same deficiencies as the others, but would require some adjustment for Node (replacewindow
withglobal
). – Waltz