local undeclared variables becoming global. Where in the document do they end up?

Viewed 84

I'm lacking understanding in what happens to an undeclared variable and where it ends up in the document. For example

var a = 1;
function b() {
  a = 10;
  return;
  function a() {}
}
b();
console.log(a);

with hoisting would become

function b () {
  function a() {}
   a = 10;
   return;
}

var a;
a = 1;
b();

console.log(a); // output 1

a = 10 is assigned to function a inside of function b. This leaves a = 1 to be assigned to the var a declaration. Now if we comment out function a we get a different output.

function b () {
 // function a() {}
   a = 10;
   return;
}

var a;
a = 1;
b();

console.log(a); // output 10

So now a = 10 is assigned to undeclared variable so it becomes global, so what exactly does that look like? Due to variable mutation it would be put at the bottom of the document like so?

function b () {
 // function a() {}

   return;
}

var a;
a = 1;
b();
a = 10;

console.log(a); // output 10

Is this correct?

1 Answers

In your case 10 is not assigned to an undeclared variable. All logic within function b is executed as soon as b is being invoked. When this happens a is already declared and 1 has has been assigned to it.

Since there is no variable a in the local variable environment of function b it is assigned to the next a it can find in parent variable environments.

you can test this behaviour by declaring a as a const initially. It will fail to reassign 10 within the function.

function b () {
 // function a() {}
   a = 10;
   return;
}

const a = 1;
b(); //TypeError: Assignment to constant variable.

Related