Reference and datatype checking, are these the same?
Question by Jon Lennart Aasenden
I have a simple function in my library that checks the validity of an object reference (object here meaning, a reference to a created HTML element, mostly DIV’s). It looks like this:
function varIsValidRef(aRef) {
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
}
While experimenting i found that this has the same effect:
function varIsValidRef(aRef) {
return (aRef) && typeof(aRef) == "object";
}
I understand there are some controversies regarding the short hand () test? While testing against various datatypes (null, undefined, integer, float, string, array) i could find no difference in the final outcome. The function seem to work as expected.
Is it safe to say that these two versions does the exact same thing?
Answer by Wouter J
No, in my opinion these functions don’t work the same:
First option
If aRef
is not undefined
or null
and the type of the var is object
it returns true.
Second option
First we convert aRef
to a boolean. Values like null
, undefined
and 0
become false
, everything else become true
. If it is true
(so not one of those values) it checks if the type is object.
So the second option return false if aRef
is 0
, something you don’t want. And it isn’t option a elegant way to check it, because you check if an object or string or something is equal to a boolean.
And at least they don’t return the same thing. The first option returns a boolean, but the second option returns the value you put in the function if (aRef)
is false:
varIsValidRef(0);
>>> 0
varIsValidRef('');
>>> ""
varIsValidRef(undefined);
>>> undefined
varIsValidref(null);
>>> null
Because JavaScript use these values as falsy values you don’t see the difference between these return values if you use if statements or something like that.
So I suggest you to use the first option.
Answer by Starx
Interesting case, but it seems logical for both to behave the same way despite being totally different. Lets see the first staement.
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
Here,
null
and undefined
both denote a false
state combined with the !
infront, makes it equal to the expression aRef
which will return true
in case both are either not null or not undefined.