Let's understand comparison between
var,letandconst.
- Variables defined with
vardeclarations are globally scoped or function scoped andletandconsthas 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
- Variables defined with
varcan be Redeclared but withletandconstcannot 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();
Varcan updated and re-declared.Letcan be updated but not re-declared.Constcannot 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();
- While
varandletcan be declared without being initialized,constmust be initialized during declaration.
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)
I thought so helpful to me! Thanks :)
If you find this post helpful, please share your feedback.
The second code block is not true. 'let' variables can be redeclared inside curly braces.