
Let, const, and var are WEIRD in JavaScript - kvizdos
https://blog.kentonvizdos.com/let-vs-const-vs-var-when-to-use-which/
======
zo-mar
I like the article overall. It’s definitely important to understand the
differences between all three variable declarations. However, I think the
article falls short when explaining how scope differs between var vs let and
const.

It’s not that let and const are “locally scoped”, but rather they are block
scoped. Whereas, var is globally or function scoped. This is a very important
distinction, and makes JavaScript way more consistent to work with.

Some contrived examples…

In this example, x is globally scoped. Once the loop finishes, it persists.
This means it can be accessed and even worst, modified outside of the for
loop.

    
    
      var someArray = [1, 2]
      for(var x = 0; x <= someArray.length; x++) {
        // do some work
      }
    
      console.log(x) // outputs: 3
      x++
      console.log(x) // outputs: 4
    

\---

In this example, x is scoped to the for loop block. Once the loop finishes,
it’s destroyed. This results in x not being defined when you access it outside
the for loop.

    
    
      var someArray = [1, 2]
      for(let x = 0; x <= someArray.length; x++) {
        // do some work
      }
    
      console.log(x) // output: x is not defined
    

\---

Cheers!

