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?
No, in my opinion these functions don’t work the same:
First option
If
aRefis notundefinedornulland the type of the var isobjectit returns true.Second option
First we convert
aRefto a boolean. Values likenull,undefinedand0becomefalse, everything else becometrue. If it istrue(so not one of those values) it checks if the type is object.So the second option return false if
aRefis0, 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: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.