It's not strict wrong, because javascript is dynamically typed. But if it happens, it could hide a wrong architecture of your function.
What happens in some cases?
In some case, JavaScript core returns null
if there is no result. Is the case of .match
function. In this case, null
is something like "I've found nothing".
In other case it returns -1
(i.e. .indexOf
). In this case it's appropriate because the return value should be an integer positive. -1
it's a way to tell us: "I've found nothing" or "I've not found a positive integer".
So why it returns in one case null
and in other way -1
for tell us the same thing?
In the first case the match
should return an Array (that's an Object
).
In the second case the indexOf
should return an integer. So -1
is more appropriate than null
, because null
it's an Object and not an integer.
Why not undefined
? because undefined
is something of undefined, like: "I've found nothing, and I don't know how tell you!". undefined
generally is used when the function should returns a String
but this string is not found. Returns ""
is not elegant because it tell us: "I've found the String, and the string is empty".
Another case could be a function that returns a Boolean
but in one case is undefined. So when you ask: "It's true or false?", it seems to says: "Neither!".
A beautiful example is this function:
isAlive(SchroedingersCat); // <--- undefined!!!
What if your function should be return a DOM element?
See what jQuery
doing.
jQuery return always an Object
. This object (instance of itself) could be empty or not.
var obj = $('#idElement') // <--- return always a jQuery object
if(obj.length == 1) {
// do something
}
This is an excellent trick in order to permit us to do a chain without force to check every time if we found something.