let and const vs var scoping

nspired

Byte Sized

Posted on September 27, 2021

let and const vs var scoping

Starting from ES6, let and const handle scoping differently from var. With let and const being available since ES6, you have no excuse to use var anymore!

You might have seen people mention that let and const are "lexically scoped", but what does that really mean?

In simple terms, it just means that the structure of your program itself shows where a scope begins and where it ends: opening a curly brace for a function creates a new scope, closing it ends the scope.

Here's an annotated code example that shows the differences between the two

function foobar(x) { // Start of a scope
  if (x == 1) { 
    // Variables declared with `var` are "hoisted"
    // and initialized to `undefined`.
    console.log(foo); // undefined
    // `let` and `const` are hoisted too, but not 
    // initialized to `undefined`.
    console.log(bar); // Uncaught ReferenceError: bar is not defined

    var foo = "foo";
    let bar = "bar";
  }

  // `foo` is scoped to the function , so it's 
  // available anywhere in the function block
  console.log(foo); // "foo"
  // `bar` is scoped to a block, here `if (x == 1) {}`,
  // so when the block ends (after the `}`), `bar`
  // isn't available anymore.
  // Any pair of curly braces `{}` creates a new block.
  console.log(bar); // Uncaught ReferenceError: bar is not defined
}
Enter fullscreen mode Exit fullscreen mode

Did you enjoy this blog post? Check us out on Twitter @nspiredTech for more tech content!

💖 💪 🙅 🚩
nspired
Byte Sized

Posted on September 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related