Const, Let, and Var

Next Story

How to implement a Queue in Python

In ES6 and beyond, Javascript will give us 3 options for creating variables.

The 3 options are Const, Let, and Var.

Var has been around as long as Javascript whereas Let and Const are newly available via ES6.

Var variables are created with functional scope and this can cause a lot of problems in your code.

function foo() {
  if(true){
    var test = "stuff";
  }
  console.log(test); // outputs "stuff"
  // test can be accessed outside the block and within the function
}

Let on the other hand is declared with block scope.

function foo2() {
  if(true){
    let test = "stuff";
  }
  console.log(test); // errors with ReferenceError: test is not defined
  // test cannot be accessed outside the block with let variables which are block scoped
}

Const differs from Let and Var in that it is created as a constant and can’t be reassigned. Const however is also block scoped.

const foo3 = "stuff";
foo3 = "more stuff"; // errors with 'TypeError: Assignment to constant variable' if you try to reassign the const

Due to the block scoping of Let and Const, it is preferable to use them over var. Minimizing the scope of your variables whenever possible will usually lead to less bugs in your code.

Also, try to use const as much as possible unless the variable needs to be reassigned, then use let.

Leave a Reply

Your email address will not be published. Required fields are marked *

https://www.googletagmanager.com/gtag/js?id=UA-63695651-4