Muhammad Abdullah
Muhammad Abdullah

Reputation: 198

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

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!

Upvotes: 3

Views: 1810

Answers (2)

pratik pokhrel
pratik pokhrel

Reputation: 11

function check() {}

if (check() == undefined) {
  console.log(undefined);
} else {
  console.log("Nothing");
}

Upvotes: -2

Quentin
Quentin

Reputation: 944204

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

Upvotes: 8

Related Questions