JS Fundamentals - Functions Flashcards

1
Q

Function Declaration

A
function showMessage() {
  alert( 'Hello everyone!' );
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

function without a return statement

A
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;
  }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

returns undefined

A

If a function does not return a value, it is the same as if it returns undefined:

function doNothing() { /* empty */ }

alert( doNothing() === undefined ); // true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

An empty return is also the same as return undefined

A
function doNothing() {
  return;
}

alert( doNothing() === undefined ); // true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Never add a newline between return and the value

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Solution

A

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)
  )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly