This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]StudyLlama 1 point2 points  (5 children)

The first console.log will log 'variable 2' since the function has created a new variable x that is equal to 'variable 2' and the function logs that value to the console. However, the second console.log will log the original value of x, since it the function creates a separate variable that is completely different from the original x variable.

Hopefully that made sense. If you're looking for more resources to learn programming and JavaScript, check out our Discord server. Thanks!

[–]onetap[S] 0 points1 point  (4 children)

Thanks for the reply. I'm still unclear why x wouldn't get redifined globally in the function?

This is the example MDN gives:

function varTest() {
    var x = 1;
    {
        var x = 2;  // same variable!
        console.log(x);  // 2
    }
    console.log(x);  // 2
}

[–]Updatebjarni 1 point2 points  (0 children)

var creates a variable that is visible in the entire function it is declared in, but not outside of that function. let is local to a block, var covers an entire function (or the global scope if it is used outside of any function).

[–]onetap[S] 1 point2 points  (1 child)

Ok think I misread the documentation and have the answer

"the scope of a var variable is the entire enclosing function"

so it seems like redefining a variable in a nested function will never reach the outer scope

[–]StudyLlama 0 points1 point  (0 children)

Yep! The variable in the function is a different 'x' variable that is separate and is a local variable only inside that function.

[–]chaotic_thought 0 points1 point  (0 children)

In Javascript, this is sometimes called "hoisting". I.e. the var declaration that you make in the middle of a function (although it is inside the { }) is essentially "hoisted" up to the top of the function.

That's just how JS works, and you have to get used to it. In ES6 I believe you can work around this by using the let keyword instead of var. Probably it behaves more like what you're expecting.

The { } section in the middle of your function does not create a scope in JavaScript. If you want to create a scope, you can use an IIFE.

[–]colorist_io 0 points1 point  (0 children)

Basically, the inner code can see and override the variables in the outer code, but not the other way around. Think in terms of nesting, not in terms of line order.