N
nick
What's the "best" way to determine if a variable is defined?
I see a lot of code that looks like this:
// example 1
if (typeof x !== 'undefined') doStuff(x);
It won't throw an exception if you use it to operate on an undeclared
or deleted identifier.
If you're only testing declared variables, which seems like a
reasonable design decision, and are targeting only modern browsers you
could write this ():
// example 2
if (x !== undefined) doStuff(x);
Here's another way you could do it... I've rarely see it written like
this, but it gives the same result and should work in older browsers:
// example 3
if (x !== void 0) doStuff(x);
The third example is the most concise. The 'void' operator has been
around pretty much forever. I'm no js optimization expert, but I can't
imagine it being much less efficient than the first example.
The third example doesn't read as well as the second example, but (to
me) it's about as clear as the first, and with less room for error
(quoted string 'undefined' can be mistyped and not caught right away).
Is there any good reason not to use the 'void' operator to check
whether something is defined, assuming the author knows the variable
has been declared? Or is this another one of those things that has
been remembered and forgotten?
function isDefined (v) { return (v !== void 0) }
I see a lot of code that looks like this:
// example 1
if (typeof x !== 'undefined') doStuff(x);
It won't throw an exception if you use it to operate on an undeclared
or deleted identifier.
If you're only testing declared variables, which seems like a
reasonable design decision, and are targeting only modern browsers you
could write this ():
// example 2
if (x !== undefined) doStuff(x);
Here's another way you could do it... I've rarely see it written like
this, but it gives the same result and should work in older browsers:
// example 3
if (x !== void 0) doStuff(x);
The third example is the most concise. The 'void' operator has been
around pretty much forever. I'm no js optimization expert, but I can't
imagine it being much less efficient than the first example.
The third example doesn't read as well as the second example, but (to
me) it's about as clear as the first, and with less room for error
(quoted string 'undefined' can be mistyped and not caught right away).
Is there any good reason not to use the 'void' operator to check
whether something is defined, assuming the author knows the variable
has been declared? Or is this another one of those things that has
been remembered and forgotten?
function isDefined (v) { return (v !== void 0) }