TLDR: Why are function parameters not treated as var
declarations?
Using var
, redeclaring a variable declared using var
has no effect. The original declaration remains in effect.
However, using var
in this way will mask a parameter of the same name.
Why is the language designed like this?
In the following, variable var bar
is treated as a new declaration and not a redeclaration of parameter bar
.
function foo(bar = 0, bam = () => bar) {
var bar = 1
return bam()
}
console.log(foo()) // 0
Is it designed like this because arguments and local variables are semantically fundamentally different, and fall into two categories?
I might have expected parameters to be treated like var
declarations, but they aren't. They appear to be in their own "box" on the scope chain.
So the scope chain of a function looks like this:
function body >> parameter list >> outer function body >> outer parameter list >> ... global scope