Variables declared with let
are block-scoped, meaning they are only accessible within the block where they are defined.
Block Scope
Blocks, such as those defined by {}
, include loops, conditional statements, and functions.
So, the variables declared with let
inside a loop, conditional statement or function can only be used inside them.
A let
variable must be declared before it is used.
Example
{
let x = 10; // x is only accessible within this block
console.log(x); // Output: 10
}
console.log(x); // Error: x is not defined
Redeclaring a let
variable in the same scope is not allowed.
Example
{
let x = "Robbin zoo";
let x = 0; // Error: Identifier 'x' has already been declared
}
Global Scope
Variables declared with var
at the top level of a script or program are always in the global scope.
Variables declared with var
do not support block scope. So, variables declared with var
inside a { }
block are accessible outside the block.
Example
{
var x = 4;
}
// x is accessible outside
console.log(x); // Output: 4
This behavior can lead to unexpected issues, so it's recommended to use let
or const
for better scoping control.
Variables declared with var
can be redeclared within the same scope, which may lead to bugs if not managed carefully:
Example (valid but risky)
var y = "Robbin Zoo";
var y = 0; // This is allowed with var
document.getElementById("message").innerHTML = y; // Output: 0
The let
keyword allows you to declare a variable with the same name in different blocks without affecting its value outside the block. This ensures variables are scoped only to the block they are declared in, preventing conflicts.
Example
<p id="message"></p>
<script>
let x = 30; // Declared in the global scope
{
let x = 8; // Redeclared in a block (different scope)
// This block's variable 'x' is 8, but doesn't affect the global 'x'
}
document.getElementById("message").innerHTML = x;
// Output: <p id="message">30</p>
</script>
Redeclaring
Variables declared with var
can be redeclared anywhere in the program, even in the same scope.
With let
, redeclaring a variable in the same block is not allowed:
Example
var x = 6; // Allowed
let x = 9; // Not allowed
{
let x = 6; // Allowed
let x = 9; // Not allowed
}
{
var x = 6; // Allowed
var x = 9; // Allowed
}
Redeclaring a variable with let
, in another block, is allowed:
Example
let x = 4; // Allowed
{
let x = 6; // Allowed
}
{
let x = 8; // Allowed
}
Using var and let
Variables declared with var
are hoisted to the top of their scope and can be initialized at any time. This means you can use the variable before it is declared.
Example:
{
x = 10;
console.log(x); // Output: 10
var x = 10;
}
Variables declared with let
are hoisted to the top of their block but are not initialized.
This means that attempting to use a let
variable before it is declared will throw a ReferenceError.
Example
{
x = 10;
console.log(x); // Output: Cannot access 'x' before initialization
let x = 10;
}