The real question might be, what happens when a function has run out of code; and, can we interrupt the code and exit the function?
To the first part, the answer is simple⦠JS resumes flow from the statement immediately following the function call, or completes any assignment and then resumes. The return value will automatically be, undefined
since the function didnāt provide a return value.
To the second part, we already know the answer⦠Yes, we can interrupt the function anywhere and force a return, with or without a return value. If we only use return
the value will be as above, undefined
.
In generalized form, the ternary example above could be written,
if (condition) {
return value
}
return default
If I understand your question, is it to do with what a function can return? Does it have to be an expression?
To the second part, yes, it must be an expression since if it is a statement that will be executed first (if it doesnāt throw an exception) and the return value will be undefined. An expression is a value, first and foremost.
The value, 'a'
is a simple string expression, as is, ""
, or 0 or 1 a numeric expression. When the return value is any expression then we can trust that it will make it back to the caller.
To the first part, it can return any object, including a function. Please let me know if Iām getting your question correctly.
> const f = function(x) {
return console.log(a = x + 5)
}
<- undefined
> f(5)
10
<- undefined
> const g = function() {
return x => x + 5
}
<- undefined
> g()(5)
<- 10
Note the outcomes.