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';
}
}
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';
}
}
Share
Improve this question
asked Jun 25, 2013 at 2:34
seamusseamus
2,9019 gold badges31 silver badges55 bronze badges
4 Answers
Reset to default 9Functions that don't return an object or primitive type return undefined. Check for undefined:
if(typeof loop(param) === 'undefined') {
//do error stuff
}
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).
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...
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";
}
}
}