Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Confused about block-level scoping

I am confused by block-level scoping. I thought I understood scope in JavaScript, but then I started taking the Intro to ES2015 course and realized I totally don't. Okay, so consider this example:

function foo() {
    const x = 1;
    if (someCondition) {
        const x = 2;
        console.log(x);
    } else {
        console.log(x);
    }
}

In this example, a constant is declared in the top scope of the function, so it is accessible in all sub-blocks. But even though it is accessible in all sub-blocks, redefiningit in a sub-block is still legal. If the else block runs, then 1 will be logged out. But if the if branch is run, the constant will be redefined and 2 will be logged out. I just don't understand how sub-blocks can have access to a constant, but also be able to redefine a constant. This is turning my brain inside out a little. If anyone could help explain the scoping of let and const to me in an intuitive way I would be extremely grateful!

1 Answer

Steven Parker
Steven Parker
230,250 Points

When you create a variable in a block with the same name as one in a larger scope it "shadows" the other one, meaning it makes the other one inaccessible. The original one is not reassigned, and in the case like this of a "const", reassigning would not be valid anyway.