2

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.

Andrei Dvoynos
  • 1,126
  • 1
  • 10
  • 32
  • See also https://stackoverflow.com/questions/44224316/some-problems-in-function-default-parameters?noredirect=1&lq=1 – Bergi Feb 26 '18 at 23:52
  • Yes, your description is correct. I don't think it's really documented anywhere in prose, as this use case is pretty exotic. – Bergi Feb 26 '18 at 23:54

1 Answers1

0

You are correct. In both of the top functions x in f refers to the parameter x.

There's some considerations with case 3.

In the third example if f isn't defined and you are returning x2 when calling the function it will be equal to whatever x originally was. When you do x = 5; you aren't changing x2. This is because when you assign x2 = x JavaScript makes a copy not a reference.

Unless the x parameter is passed an array or object x2 will be a copy and not a reference of x.

So if you do three(3) then x2 will always be 3 because you're never changing it.

notvita
  • 122
  • 1
  • 8
  • Right, I was missing the var statement for function three. With the var statements they should be the same, even with objects instead of literal values. – Andrei Dvoynos Feb 27 '18 at 14:28