How to check if a function's return value is undefined or not in Javascript

Viewed 880

Hello I'm a beginner at Javascript and I was actually wondering if I made a function like the one below:

function doSomething(){
//does something
}

After creating this function how do I know if the value returned by this function is undefined or not ? I tried the following to solve my problem:

if (doSomething == undefined){//code will do something}

and

 if (doSomething){//code will do something}

and

if (typeOf doSomething === undefined){//code will do something}

but none of them worked.

So basically the question is how do I check if the return value of this function is undefined or not. Thanks in advance for the answer!

1 Answers

You have to call the function to get a return value from it.

if (typeof doSomething() === 'undefined') {

}

If you don't call it, you don't know what it will return (which might be different depending on what you pass it or some other condition).

function doSomething(value) {
    if (value === "Nothing") return undefined;
    return "Something";
}
Related