简体   繁体   中英

Comparing undefined value in JavaScript

I have an object whose value may be undefined sometimes. So is it possible / valid / good practice to test it with an if case like below :

if(params === undefined)  
{  
    alert("sound." + params);  
}  

If not, why can't we do it?

As of now, it is working fine. Yet, I would like to know if it can go wrong anytime?

Thanks

Since in theory undefined can be redefined (at least pre-JS 1.8.5), it's better to use

if (typeof params === 'undefined')

This also works without throwing an error if params is not a known variable name.

Use typeof varName for safer usage:-

This will not throw any error if params is not a variable declared anywhere in your code.

 if(typeof params  === "undefined")
   {
       //it is not defined
   }

 if(params === undefined)   //<-- This will fail of you have not declared the variable 
        //param. with error "Uncaught ReferenceError: params is not defined "
 {
 }

Refer Undefined

The typeof answers are good, here's a bit extra. To me, this is a case where you need to explain what you are doing with params . If you are doing say:

function foo(paramObject) {
  // determine if a suitable value for paramObject has been passed
}

then likely you should be testing whether paramObject is an object, not whether it has some value other than undefined . So you might do:

  if (typeof paramObject == 'object') {
    // paramObject is an object
  }

but you still don't know much about the object, it could be anything (including null ). So generally you document the object that should be passed in and just do:

  if (paramObject) {
    // do stuff, assuming if the value is not falsey, paramObject is OK
  }

now if it throws an error, that's the caller's fault for not providing a suitable object.

The corollary is that all variables should be declared so that the test doesn't throw an error (and you don't need to use typeof , which is one of those half useful operators that promises much but doesn't deliver a lot).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM