Tip 3: Isolate Information with Block Scoped Variables

In this tip, you’ll learn how let prevents scope conflict in for loops and other iterations.

At one point or another, every developer will make the mistake of capturing the wrong variable during a for loop. The traditional solution involves some pretty advanced JavaScript concepts. Fortunately, the let variable declaration makes this complex issue disappear.

Block scoped variables

Remember, when you use a block-scoped variable declaration, you’re creating a variable that’s only accessible in the block. A variable declared in an if block isn’t available outside the curly braces. A variable declared inside a for loop isn’t available outside the curly braces of the for loop. But that doesn’t mean you can’t access variables declared outside a function. If you declare a block scope variable at the top of a function, it is accessible inside the block.

Lexically scoped variables

If you declare a lexically scoped variable, however, it’s accessible anywhere inside a function. A variable created inside an if block can be accessed anywhere else in the function. In fact, you can even access a variable before it was declared because of a compile process called hoisting.

Example

If that all seems too abstract, that’s fine. It’s easier to understand in practice. Chances are, if you’ve encountered a lexical scope issue before, it probably occurred when you were adding a click function to a series of DOM elements:

Get hands-on with 1400+ tech skills courses.