JavaScript Let
The let keyword declares a block-scoped variable whose value can be reassigned as your program runs.
When to use let
Use let for any variable whose value you expect to change over time, such as a running total, a loop counter, or a value that is recalculated based on user input. It was introduced in ES6 (2015) as a safer, more predictable replacement for var.
Reassigning a let variable
<!DOCTYPE html>
<html>
<body>
<h2>Reassigning a let variable</h2>
<script>
let score = 0;
score = score + 10; // reassignment is allowed
score += 5;
console.log(score); // 15
</script>
</body>
</html>Block scope
A variable declared with let only exists inside the block, the pair of curly braces, where it was defined. Once execution leaves that block the variable is gone. This block scoping keeps variables from leaking into unrelated parts of your code and is one of the biggest advantages of let over var.
let respects block boundaries
<!DOCTYPE html>
<html>
<body>
<h2>let respects block boundaries</h2>
<script>
let x = 10;
{
let x = 2; // a separate variable inside this block
console.log(x); // 2
}
console.log(x); // 10
</script>
</body>
</html>No redeclaration in the same scope
Within a single scope you cannot declare the same let variable twice. Attempting to do so throws a SyntaxError. This protects you from accidentally overwriting a variable you already created, a mistake that var silently allowed.
Redeclaring let throws an error
<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring let throws an error</h2>
<script>
let city = "Paris";
// let city = "London"; // SyntaxError: already declared
city = "London"; // reassignment is fine
console.log(city); // London
</script>
</body>
</html>let versus var
- let is block-scoped, while var is scoped to the whole enclosing function.
- let cannot be redeclared in the same scope; var can.
- let variables are not attached to the global window object; global var declarations are.
- Accessing a let variable before its declaration throws an error instead of returning undefined.