Let's understand comparison between
var
,let
andconst
.
- Variables defined with
var
declarations are globally scoped or function scoped andlet
andconst
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
- Variables defined with
var
can be Redeclared but withlet
andconst
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();
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();
- While
var
andlet
can be declared without being initialized,const
must 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.