How to JavaScript | Because '5' === 5

JavaScript: const vs. let vs. var - What's the difference?

const, let, and var are 3 different ways to declare a variable in JavaScript, each with different consequences in terms of scope and assignment.

const

const is short for “constant”, which alludes to how it operates- in that once you’ve assigned a value to a variable using const, you may NOT change what that variable is assigned to. In other words a variable assigned using const cannot be reassigned.

This is enforced by the JavaScript engine, so trying to reassign a const variable will throw an exception, like so:

  
    const test = {}
    test = 'hello' // TypeError: Attempted to assign to readonly property.
  

This does not mean that you can’t change the properties or state of the variable, though. This is a common misconception. Try this out:

  
    const test = {}
    test.hello = 'world' // OK 👌

    test = { another: 'object' } // TypeError: Attempted to assign to readonly property.
  

const scope

Variables declared with const stay in scope until the execution context they were created in goes out of lexical scope, typically within the global scope or a function.

let

In contrast to const, let allows you to reassign variables after they’ve been declared. For example:

  
    let test = {}
    test = { another: 'object' } // Not a problem 👌
    console.log(test) // => { another: 'object' }
  

let scope

let declarations get defined in block scope, which means that they go out of scope as soon as the block they were declared in is terminated. Here’s an example where we legally define a variable called test twice, each in a different scope:

  
    let test = 'hello world'
    if (true) {
      let test = 'hello block'
      console.log(test) // 'hello block'
    }

    console.log(test) // 'hello world'
  

In this second example, test goes out of scope after the if statement finishes, so we get a ReferenceError when we try to access it.

  
    if (true) {
      let test = 'hello block'
      console.log(test) // 'hello block'
    }

    console.log(test) // ReferenceError: Can't find variable: test
  

var

var is just like let in that you are allowed to reassign the variable. The difference is that the variable will be defined in either the global scope or the current lexical scope.

It’s also important to note that although you’re syntatically able to redeclare a a variable created with var, you’re really only reassigning the variable. It also makes for confusing code, so please don’t do this:

var scope

  
    var test = 'hello world'
    if (true) {
      var test = 'hello block'
      console.log(test) // 'hello block'
    }

    console.log(test) // 'hello block'
  

In summary

  • let & var allow you to reassign the variable
  • const does not let you reassign the variable
  • let variables are only exist until the block they were defined in terminates