JS Fundamentals - Functions Flashcards
Function Declaration
function showMessage() { alert( 'Hello everyone!' ); }
function without a return statement
function checkAge(age) { if (age >= 18) { return true; } else { return confirm('Do you have permission from your parents?'); } }
It is possible to use return without a value. That causes the function to exit immediately.
For example:
function showMovie(age) { if ( !checkAge(age) ) { return; }
returns undefined
If a function does not return a value, it is the same as if it returns undefined:
function doNothing() { /* empty */ }
alert( doNothing() === undefined ); // true
An empty return is also the same as return undefined
function doNothing() { return; }
alert( doNothing() === undefined ); // true
Never add a newline between return and the value
For a long expression in return, it might be tempting to put it on a separate line, like this:
return
(some + long + expression + or + whatever * f(a) + f(b))
That doesn’t work, because JavaScript assumes a semicolon after return. That’ll work the same as:
return;
(some + long + expression + or + whatever * f(a) + f(b))
So, it effectively becomes an empty return.
Solution
If we want the returned expression to wrap across multiple lines, we should start it at the same line as return. Or at least put the opening parentheses there as follows:
return ( some + long + expression \+ or + whatever * f(a) + f(b) )