26

In JavaScript functions, do I need to return something (true or false) ? So far, all the functions I wrote without returning anything work just fine. I'm just curious.

2
  • 1
    They work just fine unless you are expecting them to return anything other than undefined ;-) But, I think the question sort of answered itself. Commented Jun 3, 2011 at 0:36
  • 2
    Also, just because a function does return something doesn't mean you have to do anything with the returned value. Commented Jun 3, 2011 at 0:52

3 Answers 3

29

No; Javascript functions are not required to return a value.

If you call a function that doesn't return a value, you'll get undefined as the return value.

Sign up to request clarification or add additional context in comments.

3 Comments

Same goes for functions that has return; in them.
And functions that can exit with out executing one of its returns.
I think perhaps "if you call a function and return is not executed.." or ... "if control runs off the end of the function without encountering return" or ...
2

no you dont. I believe if you do

var result = iAmADefinedFunctionThatDoesntReturnAnything();

result will be undefined.

Edit, this screenshot should be illuminating (forgive the mistake when i fail to invoke f):

enter image description here

5 Comments

Actually, as you haven't defined the function, it throws ReferenceError.
@hello71. Look at the top. Line 1. var f = function(){} certainly defines a function
Also, you should really use typeof to determine undefined.
@hello71, right, i was hoping that we could intuit that functionThatDoesntReturnAnything() is actually a defined function that does not return anything. ;)
@hello71, ok how about now? ;)
1

No you don't

BUT if you find yourself doing something like this

 function myFun(){
   if (1 == 2){
    return true ;
   }
 }

Now you should know you are doing something wrong in your code because it doesn't make sense that only part of the function return a value

2 Comments

Why won't it make sense? For example if you want to populate a list with a search term and it isn't found then you might as well give nothing back.
Becuase the if condition is always evaluated to be null, which we call a dead code

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.