Function Scope Help

Hello Everyone! I was wondering if anyone could explain to me why j is declared but not initialized:

function test(o) {
var i = 0;
if (typeof o == “object”) {
var j = 0;
for(var k = 0; k < 10; k++){
console.log(k)
}
console.log(k)
}
console.log(j)
}

Here is the formatted version.

function test(o) {
  var i = 0;

  if (typeof o == 'object') {
    var j = 0;
    for (var k = 0; k < 10; k++) {
      console.log(k);
    }
    console.log(k);
  }

  console.log(j);
}

1 Like

Because, var is function scoped. So, JavaScript goes through a process called hoisting, which essentially reads all the variables and declares them. Then initializes them, later.

But, since o is not an object, it is only declared due to hoisting. And since var is function scoped, it is allowed to be used after the for loop braces

Change the var to let and you would see how let is block scoped

1 Like

Thanks for the reply! I’m getting confused because I recently learned about function scoping and I thought everything defined using var inside the function is available to anything inside that function. If it was block scoped, then j would only be available to anything inside the if statement but since javascript is function scoped, I always thought j would be accessible to everything under test function; so console.log(j) would work.

Wait, so console.log(j) would work if o is defined as an object?

Watch a youtube video on variable scopes for more explanation! Or read an excellent article on FreeCodeCamp News

I think i understand now. Could you clarify if my logic is correct please. So all three variables are declared but just o isn’t an object, j isn’t initialized and hence console.log(j) cannot work?

you kinda gave me the answer and doing some thinking, but I guess i just wanted my logic verified. I’ve been reading and watching videos but since i’m a new programmer, the learning curve is a little steep for me. Anyways thx!

You might want to continue doing some sandboxing in a code editor with formatting so you can see it visually.

I would personally take a screenshot of the code, then highlight each curly brace a different color and between it to see the scopes for learning!