Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to return something in javascript function?

Tags:

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.

like image 941
Moon Avatar asked Jun 03 '11 00:06

Moon


People also ask

Is it necessary to use return in function?

In a main function, the return statement and expression are optional.

Is it mandatory to return a value from function?

You can omit the return value of a function and use a bare return without a return value.

Should JavaScript functions always return?

Those of you who, like me, had algorithms classes might remember this : a function must always return something. It's a ground rule. JavaScript follows this rule, functions always return something. In the case where you don't want to return a value, something else exists.


2 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.

like image 83
SLaks Avatar answered Sep 29 '22 21:09

SLaks


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

like image 22
hvgotcodes Avatar answered Sep 29 '22 21:09

hvgotcodes