The difference between Const, Let and Var in JavaScript

The new ES6 features discussed in this article are const and let. We use the const and let keywords to declare variables. In this article I’ll show you the essential differences between const let and var.

Const

Const cannot be redeclared or assigned and is read-only. We use const to declare variables that do not change once assigned. It is block-scoped, meaning that once declared in {}, it cannot be accessed outside {}. Let’s look at a few examples:

Uncaught SyntaxError: Identifier ‘test’ has already been declared

So what happens if we reassign a variable? Uncaught TypeError: Assignment to constant variable So, you can’t reassign a variable declared by const.

Let

Let cannot be redeclared but can be reassigned; it is block-scoped. When we want to assign the variable again, we use let. We must declare a variable before we use it.

Identifier ‘test’ has already been declared Uncaught SyntaxError: Identifier ‘test’ has already been declared Variables declared by let cannot be declared again.

When I try to assign the variable’s value again, from “Hello” to “Hi”,console.log() returns “Hi” and does not throw an error. This means that the reassignment was successful.

When we use console.log() to print the value of variable I outside the declared block, we raise Uncaught ReferenceError: I is not defined. This is because let is block-scoped. As I explained above, we cannot access variables outside of the declared block ({}).

Var

Var can be redeclared and assigned. Var is functionally or globally scoped and can be accessed outside the block-level scope. We should avoid using var because it can cause bugs in case the developer declares variables and then redeclares them.

As shown below, this shows that we can reassign and redeclare the variable var.

Here is the difference between let const and var when accessing block-level scopes. Uncaught ReferenceError: testConst is not defined is thrown when attempting to access testConst and testVar

Examples of testConst and testLet are as follows:

The following is an example of testVar:

Here’s a summary of the differences:

The resources

  1. www.w3schools.com/js/js_scope…
  2. Developer.mozilla.org/en-US/docs/…
  3. Developer.mozilla.org/en-US/docs/…
  4. Developer.mozilla.org/en-US/docs/…