The let keyword is used to declare variables in modern JavaScript. It is a
safer and clearer alternative to var in many situations, especially
because let respects block scope and helps reduce common coding mistakes.
let in JavaScript?let creates a variable whose value can change later. If you need to store a
value now and update it later, let is often the right choice.
let score = 10;
score = 15;
console.log(score);
In this example, the variable score is first set to 10 and
then updated to 15.
letYou can declare a variable with let and assign a value at the same time:
let userName = "Rafi";
let price = 120;
let isLoggedIn = true;
You can also declare the variable first and assign the value later:
let city;
city = "Chattogram";
let Can Be ReassignedA variable created with let can receive a new value after declaration. This
makes it useful when the value may change while the program runs.
let temperature = 28;
temperature = 30;
let when you know the variable may need a new
value later. If the value should never change, const is usually a better
choice.
letOne of the biggest advantages of let is block scope. A variable declared
with let exists only inside the block where it was created. A block is
usually anything inside curly braces { }, such as an if
statement or a loop.
if (true) {
let message = "Hello";
console.log(message);
}
// console.log(message); // Error
Here, message works only inside the if block. Outside that
block, the variable does not exist.
let Cannot Be Redeclared in the Same BlockYou cannot declare the same variable name twice with let inside the same
block.
let name = "Mila";
// let name = "Sara"; // Error
This rule helps catch mistakes early. It prevents you from accidentally creating two variables with the same name in one place.
let vs varOlder JavaScript code often uses var, but modern JavaScript usually prefers
let. The biggest difference is scope.
| Feature | let |
var |
|---|---|---|
| Scope | Block scope | Function scope |
| Redeclaration in same scope | Not allowed | Allowed |
| Modern usage | Recommended | Mostly older code |
Here is a simple example showing why let is useful when a value changes over
time:
let cartTotal = 0;
cartTotal = cartTotal + 200;
cartTotal = cartTotal + 150;
console.log(cartTotal);
The value of cartTotal changes as more items are added, so
let fits this situation well.
let is used to declare variables in modern JavaScriptlet can be reassignedlet is block-scoped, so it only works inside its own blocklet variable in the same blocklet is usually preferred over var in modern codelet when the stored value may change later