The let statement declares a block-scoped local variable, optionally initializing it to a value. It can be defined using let keyword.
let x =1;
console.log(x); // Output : 1
Variables defined with let cannot be redeclared.
let x = "John";
let x = 0;
// SyntaxError: 'x' has already been declared
let is block scoped
A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.
So a variable declared in a block with let is only available for use within that block.
let str = 5;
if (str > 2) {
let hello = "Hello World";
console.log(hello); // Output : "Hello World"
}
console.log(hello) // hello is not defined
We see that using hello outside its block (the curly braces where it was defined) returns an error. This is because let variables are block-scoped.we can see another example below
let x = 10;
console.log(x); // Output : 10
{
let x = 2;
console.log(x); // Output : 2
}
console.log(x); // Output :10
let can be updated but not re-declared.
let message = "Hello World";
if (true) {
let message = "How Are you";
console.log(message); // Output : "How Are you"
}
console.log(message); // Output : "Hello World"
This gives no error because this fact makes let a better choice than var. When using let, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.
let a = 10
// It is allowed
a = 20
console.log(a); // Output : 20
From above example , we can assign different value to variable.