typeof === "undefined" vs. != null
        Posted  
        
            by Thor Thurn
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Thor Thurn
        
        
        
        Published on 2010-04-24T03:26:13Z
        Indexed on 
            2010/04/24
            3:33 UTC
        
        
        Read the original article
        Hit count: 273
        
I often see JavaScript code which checks for undefined parameters etc. this way:
if (typeof input !== "undefined") {
    // do stuff
}
This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because 'undefined' could be renamed, though. My question is: How is that code any better than this approach:
if (input != null) {
    // do stuff
}
As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (e.g. for optional function parameters). Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator. Why is this considered bad style?
© Stack Overflow or respective owner