Does an empty function body implicitly return undefined
in JS?
console.log((() => {})())
Clearly it does right? The console outputs undefined
in the example above...
// but let's do something crazy
console.log(((undefined) => undefined)("defined"));
console.log((() => {
var undefined = "defined";
return undefined;
})());
Ok so we can redeclare undefined
locally (or globally without strict mode)
console.log(((undefined) => {
var undefined = "defined_again";
})("defined"));
But the output is still undefined
, so it seems it's not implicitly returning undefined
, but instead treating the entire expression as void(expr)
.
This also seems to be the case in TypeScript:
const result = (() => {})()
// ^?: const result: void
So if the empty function body does implicitly return undefined
as outlined in the spec, then why does JS ignore lexical scope for undefined
if it's redeclared in the function body?
Obviously at the end of the day the result is undefined
, but I'm more curious about the actual implementation behavior of what is implicitly returned?
Does the empty function body actually return something?
It returns undefined
, as in the specific ECMAScript language value undefined
, not performing a variable lookup for an undefined
variable and returning whatever the lookup returns. If you want to go to the spec, you can see that the rule for a function completing normally without an explicit return
is
- Return ReturnCompletion(undefined).
where a bold undefined in variable-width font means the ECMAscript language value:
In this specification, ECMAScript language values are displayed in bold. Examples include null, true, or "hello". These are distinguished from ECMAScript source text such as
Function.prototype.apply
orlet n = 42;
.
(And yeah, it's a little awkward that ECMAScript source text is also bold.)