javascriptvarhoisting

Declaring a variable using the var keyword inside a function. Why is it undefined, behind the scenes


I'm a newbie and I want to make sure that I understood the hoisting with var correctly.

var a = 2;
var x = function() {
   console.log(a);
   var a = 1;
};
x();

When the "x" function is invoked, the answer that I get is "undefined"; So, the engine sees that in the function scope of "x" there is a variable "a" and assigns it to "undefined";

If we take out the variable "a" inside the function:

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

Then we get the answer "2", because the engine looks if there is a variable "a" inside the function "x", since it doesn't find it here, it looks in the outer/parent/global scope for the variable "a", and finds it.

Did I get everything right?


Solution

  • Yeah, you got it pretty much right. Just a small note for when you say:

    So, the engine sees that in the function scope of "x" there is a variable "a" and assigns it to "undefined";

    It's more like: only declarations are hoisted, not initializations. And declared but non-initialized variables default to undefined. See https://www.w3schools.com/js/js_hoisting.asp#midcontentadcontainer.

    For the second function, yes, that's correct—first it looks inside the function's scope, and then, since it can't find it, it looks inside the parent scope, then the parent's parent, and so on.