If you have worked in Javascript, you have already known var keyword. var keyword used to declare variable. You have also noticed nowadays developers use let keyword to declare variable. So if var keyword is already there, then what is need to bring new keyword in defining variable? How let is
difference than var? We will discuss all this topics in this article.
What is let?
The let keyword was introduced in ES6. let keyword is used to define block level variable. It means the variable created using let keyword in block can't be used out of block, for example if condition, loop etc.
Before ES6, Javascript variable had only global Scope and function Scope. So let was introduced to create block level variable.
Difference between let and var
The major difference is variables defined with let have limited scope. It can't be used out of block.
Example:
if (true) {
let x = 5;
}
console.log(x);
// Uncaught ReferenceError: x is not defined
while variables defined with var keyword have function scope, so it can be use out of block.
if (true) {
var x = 5;
}
console.log(x);
// 5
Variables defined with let keyword can't be redeclare in the same block.
Example:
let x = 5;
let x = 10;
// Uncaught SyntaxError: Identifier 'x' has already been declared
However it can be use out of the block:
let x = 5;
if (true) {
let x = 10;
console.log(x);
// 10
}
console.log(x);
// 5
While variables defined with var will change value at out of block also.
var x = 5;
if (true) {
var x = 10;
console.log(x);
// 10
}
console.log(x);
// 10
One other difference is that variables defined with let can't be used before declare. It will through error.
console.log(x);
let x = 5;
// Uncaught ReferenceError: Cannot access 'x' before initialization
While you can use variables defined with var before declaration.
console.log(x);
var x = 5;
// undefined
When to define variable with let?
let allows you to create variables with limited scope. So let is best way to use when you need to create temporary variable for block or function. This way, you don't need to remember if you have used a name for a variable before.