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?