Using the let keyword you can declare a block-scoped variable in JavaScript. Generally, we use the var keyword to declare a normal variable in JavaScript, but the variables declared using the let keyword are block-scoped.
let variable_name;
Optionally you can initialize it to a value.
let x = 1;
JavaScript let keyword example
Simple example variables defined with let
cannot be redeclared. It prevents accidentally redeclaring a variable.
<!DOCTYPE html>
<html>
<body>
<script>
let x = "Hello let";
let x = 100;
console.log(x)
</script>
</body>
</html>
Output:
Block Scoping rules
Variables declared by let
inside a { } block cannot be accessed from outside the block. The main difference is that the scope of a var
variable is the entire enclosing function:
<!DOCTYPE html>
<html>
<body>
<script>
function varTest() {
var x = 1;
{
var x = 2; // same variable!
console.log(x);
}
console.log(x);
}
varTest();
function letTest() {
let x = 1;
{
let x = 2; // different variable
console.log(x);
}
console.log(x);
}
letTest()
</script>
</body>
</html>
Output:
2
2
2
1
Global Scope
Declare variables in the main body or outside the function have a global scope to be accessed from anywhere inside or outside the function.
<script>
let x =20;
console.log("Outside function", x);
function show(){
console.log("Inside function", x);
}
show();
</script>
Function Scope
Declare variables inside the function are not allowed to access outside the function.
<script>
function show(){
let x =20;
console.log("Inside function", x);
}
show();
console.log("Outside function", x);
</script>
Error: Uncaught ReferenceError: x is not defined
Loop Scope
Let’s see the variable scope for the variables declared using both var and let. Redeclaration is not allowed using the let keyword but it is allowed using the var keyword.
let example
<script>
function LoopScope() {
let i = 4;
for (let i = 0; i < 10; i++) {
//code
}
console.log('Final value of x:', i);
}
LoopScope()
</script>
Output: Final value of x: 4
var example
<script>
function LoopScope() {
var i = 4;
for (var i = 0; i < 10; i++) {
//code
}
console.log('Final value of x:', i);
}
LoopScope()
</script>
Output: Final value of x: 10
Redeclaring
Redeclaring a JavaScript variable with var
is allowed anywhere in a program:
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
With let
, redeclaring a variable in the same block is NOT allowed:
var x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 2; // Allowed
let x = 3 // Not allowed
}
{
let x = 2; // Allowed
var x = 3 // Not allowed
}
Do comment if you have any doubts or suggestions on this JS basic keyword code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version