0
function foo(a)
{

   var b = a*2;
   function bar(c)
   {

    console.log(a,b,c);
    var c= 3;
   }
   bar(4);
   var c= 4;
   var a= 2;
}

foo(1);

Why c is not 3 here? In spite of the fact that var c= 3 , is defined in the lexical scope of bar() , Why var c =4 is picked even though it is defined below the bar() call ? Please help me understand how these values are picked and assigned to the variables.

user2991413
  • 521
  • 2
  • 9
  • 26
  • Use [this search](/search?q=%5Bjs%5D+variable+hoisting) to find lots of questions and answers on this topic, such as [this one](http://stackoverflow.com/questions/33540709/javascript-variable-hoisting) and a **bunch** of others, including the dupe target I just marked (in that case it's a global, but the answer's the same). – T.J. Crowder Aug 14 '16 at 10:29

1 Answers1

0
  1. c does not become 3 before the assignment is executed, which is after your log output.

  2. var c does not declare a new variable here, because you already have c as a parameter to the function (but you are right that if it did, the declaration would be "hoisted" --- and that is the term you want to search for to get good answers here).


Why var c =4 is picked even though it is defined below the bar() call ?

It is not "picked". In your function you see 4 because c is the function parameter and you call it as bar(4).

The c from the outside function is being shadowed by the local declaration of another c in the inner function and not accessible.

Thilo
  • 257,207
  • 101
  • 511
  • 656