I'm writing some code that needs to deal with many potential JavaScript values including so-called non-values . I'm realizing it would be very helpful to know if there are some general rules about which native JavaScript functions can return null
and which can return undefined
. Thus this question.
Of course, any variable can be assigned null
or undefined
so I'm not talking about custom code including code from libraries. I'm only referring to native JavaScript functions (including in ES6/ES2015). Also, when I refer to "functions" I mean that in a very generic sense in that I'm referring to
- global functions, e.g.
parseFloat("99.99")
- methods of built-in objects, e.g.
Math.floor(99.99)
- prototype methods, e.g.
'$99.99'.match('$')
- prototype properties, e.g.
'$99.99'.length
- operators (e.g. arithmetic, bitwise, etc.), e.g.
99.99 % 10
The following are some examples of the kind of rules I might hope for. I don't claim that any of them are correct or not. I'm just showing what I mean by categories:
All regex-matching functions (e.g.
match
,exec
,test
) can returnnull
but never returnundefined
. (I don't think that's true, as it seems thattest
never returnsnull
, but I'm not sure.)While arithmetic operators might return
NaN
, they will never returnnull
orundefined
. (Is that true?)No function from which you would normally expect a boolean will ever return
null
orundefined
. (Is that true?)Any return value that means "the empty set" (e.g. "no regex matches have been found", "no document elements with that id have been found") will always manifest itself as
null
. (Is that true?)
I'm particularly interested in edge cases, including functions used improperly, e.g. with a non-sensical parameter. For example, String.prototype.match
can return null
(e.g. 'abc'.match(Object)
) but String.prototype.includes
might never return null
(e.g. 'abc'.includes(Object)
returns false
, not null
).
If someone could add the new tag "undefined" to this question, that would be helpful. I don't have enough reputation points on 'Software Engineering' to do that.
function myCoolLibraryUtility(someFunc) { return someFunc(myConstant);}
. I now possibly need to deal with null or undefined return values from any function because the function itself will be provided not by me, the library creator, but by any library user. – Andrew Willems Nov 10 at 13:03