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...

Share:
19,103
seamus
Author by

seamus

Updated on June 04, 2022

Comments

  • seamus
    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
    seamus almost 11 years
    for other viewers do if( (typeof loop(param) ) === 'undefined') { //do error stuff } extra () important
  • José Cabo
    José Cabo over 7 years
    if ( loop(param) === undefined ) {} // Works like in the answer and is "better".
  • tonix
    tonix over 3 years
    How 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
    tonix over 3 years
    How to differentiate the two cases (implicit undefined return and explicit return undefined) from the caller side?