Var, let & Const are used to declare variables, objects and constants in JavaScript.
Var
Var keyword has been used for a longtime for variable declaration.
It is Function Scoped, it makes variables accessible only within the function boundary where it is declared.
Take a look at this snippet
function getX(){ var x = 1; } getX(); console.log(x) //ReferenceError: x is not defined
You can re-declare same variable in same scope with Var.
if (true){ var x = 2; var x = 3; } console.log(x) // 3
Let
Let was introduced in ES6ECMAScript2015.
It is Block Scoped, any code written within {}
is said to be in a Block. So, that's the restriction that ECMA wanted to implement with let, making variables inaccessible outside the block.
function exampleLet() { if (true) { let y = 20; } console.log(y); // Error: y is not defined }
Also, you cannot re-declare same variable within the same scope.
if (true){ let x = 2; let x = 3; } // SyntaxError: Identifier 'x' has already been declared
Const
Const as the name suggests is used to declare Constants.
Declaration with consts are *Block Scoped *
Constant needs to be initialized at the time of declaration, else it throws Syntax error
Re-assigning or re-declaration is not allowed, it throws Syntax or Type Error.
Check out the snippet below
if (true){ const x; } // SyntaxError: Missing initializer in const declaration if (true){ const x = 1; x = 2; // TypeError: Assignment to constant variable. } if (true){ const x = 1; const x = 2; } // SyntaxError: Identifier 'x' has already been declared const x = 2; if (true){ const x = 1; } // Output : x = 2
Strict Mode
A feature introduced in ES5, it enforces stricter parsing and error handling.
To enable strict mode, you need to put _use strict;_
at the beginning of code or function block.
// Global variable var globalVar = "I'm a global variable"; function baz() { var localVar = "I'm a local variable"; console.log(localVar); // Accessible inside the function if (true) { let blockVar = "I'm a block-scoped variable"; console.log(blockVar); // Accessible inside the block } // console.log(blockVar); // Error: blockVar is not defined (not accessible outside the block) }
Top comments (0)