0

I learned that "return" in a function means the end of the function. However, I see sometimes there is a return and sometimes not. Isn't it supposed to use "return" for all functions?

Yerim Kang
  • 201
  • 1
  • 4
  • 11

2 Answers2

3

You use return in two situations:

  1. You need to exit the function before reaching the end.

  2. You need to send a result to the caller.

If you reach the end of a function, it's as if the function ended with return undefined;.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can omit return from your function if it just does something without producing a value, and you don't need to exit early. You could also think of functions that don't have a return as having one implicitly at the end of the body. For example:

function noReturn() {
    console.log("Hello World");
}

function withReturn() {
    console.log("Hello World");
    return;
}

function withReturnUndefined() {
    console.log("Hello World");
    return undefined;
}

are identical.

CRice
  • 29,968
  • 4
  • 57
  • 70