Difference Between var, let, and const Keywords in JavaScript

In this article, we explain the importance of these three keywords in JavaScript and provide examples to show you how to use them.

Var

The JavaScript variables statement is used to declare a variable and, optionally, we can initialize the value of that variable.

Example: var a =10;

  1. Variable declarations are processed before the execution of the code.
  2. The scope of a JavaScript variable declared with var is its current execution context.
  3. The scope of a JavaScript variable declared outside the function is global.

Consider the following code snippet.

function nodeSimplified(){
  var a =10;
  console.log(a);  // output 10
  if(true){
   var a=20;
   console.log(a); // output 20
  }
  console.log(a);  // output 20
}

In the above code, you can find, when the variable is updated inside the if loop, that the value of variable “a” updated 20 globally, hence outside the if loop the value persists. It is similar to the Global variable present in other languages. But, be sure to use this functionality with great care because there is the possibility of overriding an existing value.

let

The let statement declares a local variable in a block scope. It is similar to var, in that we can optionally initialize the variable.

Example: let a =10;

  1. The let statement allows you to create a variable with the scope limited to the block on which it is used.
  2. It is similar to the variable we declare in other languages.

Consider the following code snippet.

function nodeSimplified(){
  let a =10;
  console.log(a);  // output 10
  if(true){
   let a=20;
   console.log(a); // output 20
  }
  console.log(a);  // output 10
}
It is almost the same behavior we see in most language.
function nodeSimplified(){
  let a =10;
  let a =20; //throws syntax error
  console.log(a); 
}

Error Message: Uncaught SyntaxError: Identifier ‘a’ has already been declared.

However, with var, it works fine.

The scope will be well maintained with a let statement and when using an inner function the let statement makes your code clean and clear.

function nodeSimplified(){ 
  var a =10;   
  var a =20;   
  console.log(a);  //output 20 
}

I hope the above examples will help you better understand the var and let commands and if you have any queries please write me in the comment section.

const

const statement values can be assigned once and they cannot be reassigned. The scope of const statement works similarly to let statements.

Example: const a =10;

function nodeSimplified(){
  const MY_VARIABLE =10;
  console.log(MY_VARIABLE);  //output 10 
}

As per usual, naming standards dictated that we declare the const variable in capital letters. const a =10 will work the same way as the code given above. Naming standards should be followed to maintain the code for the long run.