let
The let
keyword in JavaScript is used to declare variables with block scope. It was introduced in ES6 (ECMAScript 2015) as an improvement over var
, which had function scope and caused issues in larger programs.
let
To declare a variable using let
, the syntax is:
let variableName = value;
Unlike const
, let
variables can be updated, but they cannot be redeclared in the same scope.
let user = "Alice";
console.log(user); // Output: Alice
You can change the value of a let
variable:
let age = 25;
age = 30; // ✅ Allowed (Updating the value)
console.log(age); // Output: 30
However, you cannot redeclare the same variable in the same scope:
let age = 25;
let age = 30; // ❌ Error! 'age' has already been declared
let
is Block-ScopedA block in JavaScript refers to any section of code enclosed in {}
.
let
exist only within the block where they are defined.if (true) {
let message = "Hello, World!";
console.log(message); // ✅ Works inside the block
}
console.log(message); // ❌ Error! 'message' is not defined outside the block
message
was declared inside the {}
block, it does not exist outside it.for (let i = 0; i < 3; i++) {
console.log(i); // ✅ Works inside the loop
}
console.log(i); // ❌ Error! 'i' is not accessible outside the loop
let
Allows Reassignment But Not Redeclarationlet city = "New York";
city = "Los Angeles"; // ✅ No error, value is updated
console.log(city); // Output: Los Angeles
let city = "New York";
let city = "Chicago"; // ❌ Error! 'city' has already been declared
let
vs var
vs const
Feature | let |
var |
const |
---|---|---|---|
Scope | Block-scoped | Function-scoped | Block-scoped |
Can be Reassigned? | ✅ Yes | ✅ Yes | ❌ No |
Can be Redeclared in the Same Scope? | ❌ No | ✅ Yes | ❌ No |
Hoisting Behavior | ✅ Hoisted but not initialized | ✅ Hoisted and initialized with undefined |
✅ Hoisted but not initialized |
Use Case | Variables that change | Older JavaScript code | Fixed values |
var
vs let
)function example() {
var a = 10;
let b = 20;
if (true) {
var a = 30; // ✅ Redeclares 'a' (var is function-scoped)
let b = 40; // ✅ Creates a new 'b' (let is block-scoped)
}
console.log(a); // Output: 30 (var leaks outside block)
console.log(b); // Output: 20 (let is block-scoped)
}
var
leaks outside of the block, while let
does not.
let
JavaScript hoists variables declared with var
, let
, and const
, but only var
gets initialized with undefined
.
let
variables are hoisted but are not initialized.console.log(name); // ❌ Error! Cannot access 'name' before initialization
let name = "John";
The variable name
is hoisted but remains in a "temporal dead zone" until initialized.
let
✔ Use let
when a variable’s value needs to change.
✔ Avoid var
unless working with older code.
✔ Use const
for values that should not change.
✔ Declare variables as close to their usage as possible.
@asadmukhtar