Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should functions always return something (Javascript)

Tags:

function

Should functions always return something? I often write very basic functions which are used as shorthand to do things that happen a lot such as:

function formsAway() {
    $("#login_form, #booking_form").slideUp();
}

Should this function exist - is there a better way, or is this fine?

like image 306
Rich Bradshaw Avatar asked Aug 05 '10 13:08

Rich Bradshaw


People also ask

Does a JavaScript function have to return something?

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.

Do functions always need to return something?

Answer. NO, a function does not always have to have an explicit return statement. If the function doesn't need to provide any results to the calling point, then the return is not needed.


2 Answers

They don't have to return anything. If you leave it blank it simply returns 'undefined' which in this case is fine because you never intend to use the return value. The Javascript syntax is pretty simplistic and as far as I know there just isn't any real distinction between functions that do and functions that don't return a value (other than the 'return' keyword)

like image 141
Matt B Avatar answered Sep 18 '22 13:09

Matt B


All JavaScript functions return something. If an explicit return is omitted, undefined is returned automatically instead. When a function returns, its instance is wiped out from memory, which also frees all the variables in its scope to be wiped out if nothing else points to them. Without a forced return memory management would have to be done manually.

like image 29
tony Avatar answered Sep 18 '22 13:09

tony