javascript – typeof !== undefined vs. != null

javascript – typeof !== undefined vs. != null

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

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 its good enough for me 🙂

Otherwise, youll have to use typeof to avoid a ReferenceError.

If you expect undefined to be redefined, you could wrap your code like this:

    // undefined is now what its supposed to be

Or obtain it via the void operator:

const undefined = void 0;
// also safe

javascript – typeof !== undefined vs. != null

good way:

if(typeof neverDeclared == undefined) //no errors

But the best looking way is to check via :

if(typeof neverDeclared === typeof undefined) //also no errors and no strings

Leave a Reply

Your email address will not be published.