2020 Update
One of my reasons for preferring a typeof
check (namely, that undefined
can be redefined) became irrelevant with the mass adoption of ECMAScript 5. The other, that you can use typeof
to check the type of an undeclared variable, was always niche. Therefore, I'd now recommend using a direct comparison in most situations:
myVariable === undefined
Original answer from 2010
Using typeof
is my preference. It will work when the variable has never been declared, unlike any comparison with the ==
or ===
operators or type coercion using if
. (undefined
, unlike null
, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above).
if (typeof someUndeclaredVariable == "undefined") {
// Works
}
if (someUndeclaredVariable === undefined) {
// Throws an error
}