typeof is safer as it allows the identifier to never have been declared before:
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
Answer from seanmonstar on Stack Overflowtypeof is safer as it allows the identifier to never have been declared before:
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
If the variable is declared (either with the var keyword, as a function argument, or as a global variable), I think the best way to do it is:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
Otherwise, you'll have to use typeof to avoid a ReferenceError.
If you expect undefined to be redefined, you could wrap your code like this:
(function(undefined){
// undefined is now what it's supposed to be
})();
Or obtain it via the void operator:
const undefined = void 0;
// also safe
"undefined" === typeof(var)" vs "typeof(var) === "undefined"
`typeof window === "undefined"` not simplified when `--define:window=undefined`
If (typeof s== "undefined") vs if (s == undefined)... both do exactly the same thing?
Check for undefined variable isn't working
Can I use typeof on undeclared variables in JavaScript?
What does the typeof operator do in JavaScript?
How can I check if a variable is an array in JavaScript?
Videos
I’ve seen this behavior for years, but I’m trying to understand if there’s a real-world use case where typeof undefined === "undefined" is practically useful, versus just a quirky historical thing.
For example, in older codebases, I see checks like if (typeof myVar === "undefined"), but nowadays with let, const, and even nullish coalescing, this feels outdated.
So — is there a valid modern use case for typeof undefined comparisons, or is it mostly just something legacy that we put up with?