2

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

3
  • As per my view, it will work everytime. Commented May 9, 2013 at 2:53
  • if you're specifically checking for undefined, that should be fine. by undefined, if you include an empty string, 0, null, etc. then that won't catch those. Commented May 9, 2013 at 2:53
  • Just to nit-pick, objects don't have a value, they have properties. What you mean is that you have a variable that may reference an object, or it might be undefined. Commented May 9, 2013 at 3:07

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Nowadays (it is 2023), we are able to use such things like this: if ( params === undefined ) { do something }. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.