Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference and datatype checking, are these the same?

Tags:

javascript

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?

like image 384
Jon Lennart Aasenden Avatar asked Dec 07 '25 03:12

Jon Lennart Aasenden


1 Answers

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.

like image 92
Wouter J Avatar answered Dec 08 '25 15:12

Wouter J