Search code examples
javascripthoisting

What happens when two variables hoisting with the same name?


So if i declare two variables like this:

var a = 5;
var b = 10;

Javascript compiles code and until the assignment occurred these variables are undefined.

But if i write like that:

var a = 5;
var a = 10;

what happens when these variables hoisting?They both have name a and they are undefined?Or maybe it's one variable and undefined is written twice in it?


Solution

  • Hoisting isn't really relevant here. You can't have two variables with the same name in the same scope. As many times as you write var a, there is just one variable a, which is hoisted no differently than if you had a single var a.

    This code...

    function() {
      var a = 5;
      var a = 10;
    }
    

    is functionally equivalent to this code, with a hoisted:

    function () {
      var a;
      a = 5;
      a = 10;
    }