What\'s the best way of checking if an object property in JavaScript is undefined?
I use if (this.variable)
to test if it is defined. A simple if (variable)
, recommended in a previous answer, fails for me.
It turns out that it works only when a variable is a field of some object, obj.someField
to check if it is defined in the dictionary. But we can use this
or window
as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:
if (this.abc)
alert("defined");
else
alert("undefined");
abc = "abc";
if (this.abc)
alert("defined");
else
alert("undefined");
It first detects that variable abc
is undefined and it is defined after initialization.