Reputation: 6134
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
Upvotes: 2
Views: 4335
Reputation: 123739
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 "
{
}
Upvotes: 2
Reputation: 147343
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).
Upvotes: 1
Reputation: 234795
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.
Upvotes: 3