DEV Community

Sushil Choudhari
Sushil Choudhari

Posted on

Difference between let , const and var in Javascript

In this blog, we will discuss the javascript keywords var, let and const.
After ES6 it's a bit confusing to understand this keyword and how they work inside the javascript.

Let's start the scope of let, var and const

Scope
let:- variables declared in let's are in the block scope

const:- variables declared in const are also in the block scope

var:- variable declared with var is in the functional scope

function abc () {
var a=10
}
console.log(a) // gives an error
for(let i = 0;i<2;i++){
    console.log( i ) // print 1 2 
}
console.log(i) // gives an error
{
const b=1;
console.log(b)// print 1
}
console.log(b)// gives an error
Enter fullscreen mode Exit fullscreen mode
  • for var, it shows the error because its is functional scope so it cant accessible outside the function
  • for let inside the for loop block, it prints the output but outside the block, it gives an error as let is blocked scope
  • for const inside the curly braces, it prints the value but outside braces give an error as it is also a block scope

Let's check Reassigning values to let, const and var

  • var:- reassigning is allowed
  • let:- reassigning is allowed
  • const:- reassigning is not allowed
var a = 1 ;
a = 2;
console.log(a) // print 2
let l = 1; 
l = 2 ;
console.log(l) // print 2
const c = 1 ;
c=2
consol.log(c) // give an error 
Enter fullscreen mode Exit fullscreen mode
  • for var reassigning of value shows most recent value 2
  • for let also reassigning of value shows most recent value 2
  • for const reassigning of value gives an error as reassigning is not allowed

Let's check for Redeclaration of let, const and var

  • let:- Redeclaration is not allowed
  • var:- Redeclaration is allowed
  • const:- Redeclaration is not allowed
var v = 1;
var v = 20;
console.log(v);// prints 20
let i = 1;
let i = 20;
console.log(i); //  gives an error
const c = 1;
const c = 20;
console.log(c) // gives an error 
Enter fullscreen mode Exit fullscreen mode
  • for var, there is no error and prints the most recent declared value
  • for let and const there is an error as it does not allow the redeclaration of variable

These are some of the differences between let , const and var, hope you like it

Top comments (0)