Javascript/Jquery-How to check if a function returns any value at all?
19,103
Solution 1
Functions that don't return an object or primitive type return undefined. Check for undefined:
if(typeof loop(param) === 'undefined') {
//do error stuff
}
Solution 2
A function with no return
will return undefined
. You can check for that.
However, a return undefined
in the function body will also return undefined
(obviously).
Solution 3
You can do this :
if(loop(param) === undefined){}
That will work everytime with one exception, if your function return undefined
, it will enter in the loop. I mean, it return something but it is undefined...
Author by
seamus
Updated on June 04, 2022Comments
-
seamus almost 2 years
Is there a way to check if a function returns ANY value at all. So for example:
if(loop(value) --returns a value--) { //do something } function loop(param) { if (param == 'string') { return 'anything'; } }
-
seamus almost 11 yearsfor other viewers do if( (typeof loop(param) ) === 'undefined') { //do error stuff } extra () important
-
José Cabo over 7 yearsif ( loop(param) === undefined ) {} // Works like in the answer and is "better".
-
tonix over 3 yearsHow can I discriminate between a function which didn't return anything (e.g.:
function a() {} var ret = a(); // typeof ret === "undefined"
) and a function which explicitly returned undefined (e.g.:function a() { return void 0; // Returns undefined explicitly } var ret = a(); // typeof ret === "undefined"
)? Is there a way to know (from the caller side) that a function has returned through a return statement instead of implicitly? Thank you -
tonix over 3 yearsHow to differentiate the two cases (implicit
undefined
return and explicitreturn undefined
) from the caller side?