3

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?

mrReiha
  • 908
  • 6
  • 24
larry burns
  • 189
  • 1
  • 9
  • "*would it be put at the bottom of the script?*" - no, it stays inside the function! As usual, the statement is executed when the function is called (in `b();`). It's just that the identifier `a` now refers to a different (non-local) variable - in the same way that `console` does refer to the global variable, and still would if you put the `console.log()` call inside the function. – Bergi Dec 23 '18 at 19:22

1 Answers1

0

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.