DEV Community

Akshay Kurhekar
Akshay Kurhekar

Posted on

Var vs Let vs Const in JavaScript

Let's understand comparison between var, let and const.

javascript

  • Variables defined with var declarations are globally scoped or function scoped and let and const has block scope or we can say local scope.

example:

var testVar = 'var'; // global scope
let testLet = 'let'; // local scope
const testConst= 'const'; // local scope

function testScope {
  consol.log(window.testVar); // var
  consol.log(window.testLet); // undefined
  consol.log(window.testConst); // undefined
}

testScope() // output var
Enter fullscreen mode Exit fullscreen mode
  • Variables defined with var can be Redeclared but with let and const cannot be Redeclared.

example :

var testVar = 10; 
let testLet = 10;
const testConst = 10;

function test{
   var testVar = 20; // it will work
   let testLet = 20; // it will throw error
   const testConst = 20; // it will throw error

console.log(testVar,testLet,testConst); 
}

test(); 
Enter fullscreen mode Exit fullscreen mode
  • Var can updated and re-declared.
  • Let can be updated but not re-declared.
  • Const cannot be updated and re-declared.

example :

var testVar = 10; 
let testLet = 10;
const testConst = 10;

function test{
   testVar = 20; // it will work
   testLet = 20; // it will work
   testConst = 20; // it will throw error

console.log(testVar,testLet,testConst); 
}

test(); 
Enter fullscreen mode Exit fullscreen mode
  • While var and let can be declared without being initialized, const must be initialized during declaration.

diffrence between var vs let vs const

This all about var, let and const.

Got any question or additions? Please let me know in the comment box.

Thank you for reading πŸ˜ƒ.

Top comments (3)

Collapse
 
ali3nnn profile image
Alex Barbu • Edited

The second code block is not true. 'let' variables can be redeclared inside curly braces.

Collapse
 
adersonbertim profile image
Aderson Bertim

I thought so helpful to me! Thanks :)

Collapse
 
akshaykurhekar profile image
Akshay Kurhekar

If you find this post helpful, please share your feedback.