Here in the ECMAScript docs it details FunctionDeclarationInstantiation and on line 28 it details how the scope is created, although line 30 also seems to show a scope could be created, but it seems this is the correct line.
In NOTE 1, it also states:
If default value parameter initializers exist, a second Environment Record is created for the body declarations
A separate scope is created for default parameters:
function sum(a = 1, b = () => a) {
return a + b()
}
But I have a few questions,
1.) Are the parameters initialized as var
declarations or let
declarations or neither?
2.) Why is the second code snippet creating a block for const c = 3
whereas in the first snippet only an expected local scope is created?
here const c = 3
is in local scope
function sum(a, b) {
debugger
const c = 3
return a + b
}
here const c = 3
is in a block scope
function sum(a = 1, b = 2) {
debugger
const c = 3
return a + b
}
3.) If a new scope is created, why does the first code snippet work as expected by having two var a
variables, but in the second snippet, the compiler complains there is a re-declaration?
function sum(a = 1, b = 2) {
debugger
var a = 3
return a + b
}
I would expect to have two const a
variables here as well.
function sum(a = 1, b = 2) {
debugger
const a = 3
return a + b
}