ES6 introduced default parameters. I'm trying to understand how inline function default parameters work with this new feature. Specifically how its scoping work.
Take for example the following two functions:
function one(x, f = function (){return x})
{
var x = 5;
console.log([x,f()]);
}
function two(x, f = function (){return x})
{
x = 5;
console.log([x,f()]);
}
one(1);//[5,1]
two(1);//[5,5]
Is it correct to say that, in function one, f
keeps it's own closure scope for x
in the parameter list, so that when the function redefines x as a new var: var x = 5;
, the reference that f
has, is not the same as the one inside the function?
If that's the case, is function one equal to function three below:
function three(x,f)
{
var x2 = x;
f = f !== undefined ? f : () => x2;
var x = 5;
console.log([x,f()]); //[5,1]
}
I tried, without luck, to find how this behavior is documented, if someone could point me to the right part of the documentation that would also be great.
You are correct. In both of the top functions
x
inf
refers to the parameterx
.There's some considerations with case 3.
In the third example if
f
isn't defined and you are returningx2
when calling the function it will be equal to whateverx
originally was. When you dox = 5;
you aren't changingx2
. This is because when you assignx2 = x
JavaScript makes a copy not a reference.Unless the
x
parameter is passed anarray
orobject
x2
will be a copy and not a reference ofx
.So if you do
three(3)
thenx2
will always be 3 because you're never changing it.