Variables with the same name, but the local scope variable isn't being used, why?

倾然丶 夕夏残阳落幕 提交于 2019-11-28 14:42:08

You have declared a variable named a three times.

  • Once as a global on line 1: var a = 15;
  • Twice inside the function:
    • Once with a var statement on line 4: var a;
    • Once with an argument definition on line 3: function checkScope(a) {

The line 4 var has no effect. The variable is already declared.

Then you call checkScope(a); which passes the value of the global a (15) to the local a argument of checkScope. This is why it is 15 and not undefined.


Since they're re-declared, If I'm interpreting MDN correctly, does that mean line 3 is basically ignored?

var a is basically ignored.

But I don't think so because both variable are declared in their own, separate execution contexts

This is where you are being tripped up by having three and not two declarations of a. It declares the variable defined by the function argument name.

If you redeclare a JavaScript variable, it will not lose its value.

take a look at this answer.

var a = 15;

function checkScope(a) {
    var a; // this is equivalent to redeclaring the variable
    console.log(a); // log outputs 15 and not undefined
}

checkScope(a);

Basically line 4

var a;

is where the compiler finds a redeclared variable of the function parameter. Because of the missing initializing, a keeps the value of the handed over value of the parameter a.

Consider 'a' to be different assigned variable for arguments in function and inside as a local variable.

function a != var a;

Now, some 'a' is called by console.log(a). Now, it will search for the default 'a' value if existing, i.e, 'a' of function. Even on manipulation of 'a',

function hoist(a) {
      var a;
      a*=2;
      console.log(a);
}

hoist(10);

output: 20

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!