Function returns undefined at end of if statement even though not asked

As shown the code returns undefined below the error message.
As I understand it an if statement runs a block if the condition is true, in the given case all conditions are false therefore it should run the final ‘else’ block… which only prints a message to console and does not ask the function to return a value.

Why does it do this and how do i prevent it?

getUserInput is returning undefined because it is getting to the end of the codeblock without having returned something, so it returns undefined. Some useful info in the second paragraph in the MDN.

Now how can you prevent this. You could simply have a conditional statement that will only run a console.log if the returned value from getUserInput is not undefined

@codeneutrino since this is a function, a variable declaration is not needed.

1 Like

Hey thanks for the reply and the info page!
That’d explain it I think, but I cannot get this preventative part to work.
I tried one like

} else if (userInput !== undefined) {
console.log(“error”);
} else {};

but this returns the code from the block that is supposed to run only when userInput is NOT undefined, AND then returns ‘undefined’ below that… sure it can be undefined but why did that condition return true?

It’s fine that the function returns undefined but could you give an example solution for how to stop it printing that?

You’re mixing up when and where undefined is getting logged into the console. The function itself has nothing to do with the returned value being logged.

1 Like

Oh I see what you mean!
Do you know a way to call the function so that it will print the error message without printing ‘undefined’?

That is where a conditional statement would come in. Some pseudo code would be “if this returned value is not undefined then console.log it, if it is undefined do something else or do nothing.”

1 Like

image

This is what I’ve come up with, seems a bit unwieldy with the other two functions but it does the trick. If you have a better solution I’d be happy to hear it.

Thanks for the help :slight_smile:

Personally I would do something like this

if(result != undefined)
  console.log(result);

//Don't need an else