0

javascript code like this

function foo (x = 2,y = function(){return x;}){
   var x = 5;
   console.log(y())  // 2
}
foo(); 

console output 2,it's looks like the parameters has own scope and closure the parameter x .until i see this result:

function foo (x = 2,y = function(){return x;}){
  x = 5;
  console.log(y()) // 5  WTF?
}
foo();

console output 5.this is really confused me.Is keyword var make a redeclaration and be ignore?but looks not work like this. How this code really work in this case?

  • @sp00m No global variable, no. It's still a local variable declared by the named parameter. – Bergi Apr 19 '18 at 10:55

1 Answers1

0

Scope of x is localized when var/let/const is used.

When y is defined y = function(){return x;} in the argument list, scope of x and y is defined when the expression is evaluated at the time of definition of function foo.

While, when var is used, scope of x is localized again and older y still retain older bindings of x.

These values are not overwritten even if you pass parameters to foo

foo(1,function(){});

still outputs 5 if the var wasn't used (and the variable's scope wasn't localized hence new value is used), however with var the value is overwritten and it gives 1.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94