The difference between Var, Let and Const in JavaScript

The difference between Var, Let and Const in JavaScript

Since the creation of Javascript in 1995, It has been the most widely used website language to add functionalities and customizations to a website. Over the years, As modernization and Technology grow; there has been the need to standardize the JavaScript codes. ECMA was met with the significant responsibility to standard JavaScript code which led to the creation of Let and Const and declarations. Var had been the commonly used declaration term before the introduction of Let and Var in ES6.

What is Var

Var is a declaration word used to declare variables. In javascript, we can easily overwrite variable declaration using var. If we wrote a code using a variable name, we can redeclare that variable and reassign another value. This redeclared variable can take a new value and it will not throw any kind of error. This can be dangerous to debug. If we ever need to change a variable, we can use the 'this' keyword or try out another by assigning the variable name directly to a new value.

Features

  1. It is globally scoped
  2. It is functionally scoped.
  3. It can be re-declared.
  4. It can be re-assigned.

What is Let

Let keyword is used to declare a variable as well but it does not allow the re-declaration of a variable. If you try to re-declare a variable, it throws an error that says 'variable has already been declared. We can modify a declared variable value by re-assigning another value to it. Let have been poised to be used for variable declaration instead of var. For example: Let game = 'xbox'; game = 'Pes'; Let game = 'PES'; // throws an error

Features

  1. It is functionally scoped.
  2. It can declare a block-scoped variable.
  3. It can be re-assigned.

What is Const

Const is also used to declare variables similar to Var and Let but it has some features that are different from others. It cannot be re-declared nor can it be reassigned to another value. Const variables values are constant and can never be changed once declared and assigned. For example: Const pi = 3.14; pi = 5; // throws an error Const pi = 5; // throws an error

Features

  1. It cannot be re-assigned.
  2. It can be declared in a function scope.