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

198 views Asked by At

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?

3

There are 3 answers

0
Dennis Hackethal On BEST ANSWER

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.

5
Ryan Wheale On

In short, when you do this:

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

Javascript "hoists" your variable declarations before it interprets your code, basically converting your code to this:

var a = 2;
function() {
   // there a now new "a" variable which is undefined
   var a; 
   console.log(a);
   a = 1;
}

When JS resolves a variables, it crawls up the function scopes until it finds a variable matching the one you want. When the inner "a" variable is hoisted, it essentially overrides your outer "a" variable. Back in the day it was good practice to declare all your variables "up top" to prevent any weird unexpected issues from hoisting. The hoisting problems do not exist with const and let - which is why most code today is written with those instead of var.

1
raj On

You are trying to access before initialization inside local memory of function x(). Hoisting happens inside function local memory and x will be initialized with undefined.