JS Let
let declares a block-scoped variable that you can reassign. It replaces var for almost every modern use case.
Block scope vs. function scope
JS
// let is block-scoped
{
let x = 1;
}
// console.log(x); // ReferenceError — x doesn't exist out here
// var is function-scoped (legacy)
{
var y = 2;
}
console.log(y); // 2 — leaks out of the block
let in loops — the gotcha let solves
JS
// With let, each iteration gets its own i
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 0, 1, 2
}
// With var, all three closures share one i
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 3, 3, 3
}
let | var | |
|---|---|---|
| Scope | Block | Function |
| Redeclare in same scope | Error | Allowed |
| Hoisted | Yes, but in TDZ until declared | Yes, initialized as undefined |
| Global declaration becomes a window property | No | Yes |
Tip: Use
let when you need to reassign. Reach for const first; only switch to let if the value will actually change.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Let!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Declare a counter you can reassign.
count = 0;
Block-scoped, reassignable.
Discussion
Loading…