2

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';
    }
}

4 Answers 4

9

Functions that don't return an object or primitive type return undefined. Check for undefined:

if(typeof loop(param) === 'undefined') {
    //do error stuff
}
Sign up to request clarification or add additional context in comments.

3 Comments

for other viewers do if( (typeof loop(param) ) === 'undefined') { //do error stuff } extra () important
if ( loop(param) === undefined ) {} // Works like in the answer and is "better".
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
3

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

1 Comment

How to differentiate the two cases (implicit undefined return and explicit return undefined) from the caller side?
1

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

Comments

1

If you want to do something with the output of your function in the case it returns something, first pass it to a variable and then check if the type of that variable is "undefined".


Demo

testme("I'm a string");
testme(5);

function testme(value) {
  var result = loop(value);
  if(typeof result !== "undefined") { 
    console.log("\"" + value + "\" --> \"" + result + "\"");
  } else {
    console.warn(value + " --> " + value + " is not a string");
  }

  function loop(param) {
    if (typeof param === "string") {
      return "anything";
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.