Reputation: 35539
I am getting the following JavaScript error:
'value' is null or not an object
Can someone please let me know what is the best way to check whether an object's value is NULL in JavaScript as I have been using:
if ((pNonUserID !== "") || (pExtUserID !== "")){
Is this correct or is there a better way?
Upvotes: 2
Views: 50137
Reputation: 13
null, undefined and empty string is consider as false in conditional statement.
so
if(!n) alert("n is null or undefined or empty string");
if(n) alert("n has some value");
therefor, inflagranti suggested condition will work perfectly for you
if(pNonUserID && pExtUserID) {
}
Upvotes: 0
Reputation: 552
The !== operator returns true when two variables are not the same object. It doesn't look at the values of the objects at all
To test if something is null:
myVar == null
Your code was testing to see if the variable 'pNonUserId' referred to the same object as "", which can never be true as "" will always be a new instance of the empty string.
As an aside, a test such as:
var n = something();
// do stuff
if (n)
doSomethingElse();
Is a bad idea. If n was a boolean and false, but you were expecting the if block to test nullify you'll be in for a shock.
Upvotes: 3
Reputation: 21184
if (pNonUserID && pExtUserID)
{
// neither pNonUserId nor pExtUserID are null here
}
Any Javascript variable automatically evaluates to true when it references an object.
What you were doing are comparisons to empty strings, which are not the same as null.
Upvotes: 0
Reputation: 28125
You don't have to do that:
var n=null;
if(n)alert('Not null.'); // not shown
if(!n)alert('Is null.'); // popup is shown
Your error implies otherwise:
var n=null;
alert(n.something); // Error: n is null or not an object.
In the case above, something like this should be used:
if(n)alert(n.something);
Upvotes: 13