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.
3 Answers
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.
3 Comments
Alxandr
Same goes for functions that has
return; in them.Jeremy
And functions that can exit with out executing one of its returns.
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):

5 Comments
Hello71
Actually, as you haven't defined the function, it throws ReferenceError.
hvgotcodes
@hello71. Look at the top. Line 1. var f = function(){} certainly defines a function
Hello71
Also, you should really use typeof to determine undefined.
hvgotcodes
@hello71, right, i was hoping that we could intuit that functionThatDoesntReturnAnything() is actually a defined function that does not return anything. ;)
hvgotcodes
@hello71, ok how about now? ;)
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
Alexander
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.
Mina Gabriel
Becuase the if condition is always evaluated to be null, which we call a dead code
undefined;-) But, I think the question sort of answered itself.