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?
Asked
Active
Viewed 77 times
0
-
1well sometimes there is a need to exit and sometimes there is not. – epascarello Nov 02 '17 at 00:45
-
1And [What does javascript function return in the absence of a return statement?](https://stackoverflow.com/q/1557754/4642212). – Sebastian Simon Nov 02 '17 at 00:46
2 Answers
3
You use return
in two situations:
You need to exit the function before reaching the end.
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