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?
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With