I'm currently writing some code that wrappers user-written JavaScript functions, and have come across a point in the logic where I would like to trigger a particular behaviour if the function in question never returns a value i.e. the return keyword is never evaluated.
Currently I am assuming that if a function returns undefined, it has not returned, however this is not strictly true—due to the fact a function can always return undefined, or return the value of an undefined property.
With a function call you can always tell how many parameters were used due to the arguments.length property, I was wondering if anyone knew of a similar trick for a function's return value?
So, is it possible to tell the difference between the return values of a, b or even c
var a = function(){ };
var b = function(){ return undefined; };
var c = function(){ if(1){}else{return undefined;}; };
No, you cannot reliably, cross-browser, tell whether a function returned by just reaching the end of its code, using return without a value, or using return undefined. This is covered by Section 13.2.1 of the specification.
Another answer here suggests you could do it by analyzing the source code of the function. However, there is no standard mechanism for doing that. Though nearly all browsers make some form of the source available from Function#toString, some do not (mostly mobile browsers), and it is not defined by the specification. But if you have a certain set of browsers that you support, and they all have it, that would be your only real option — but even then, you wouldn't necessarily know which code branch was taken within the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With