iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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
}
letvar
ScopeBlockFunction
Redeclare in same scopeErrorAllowed
HoistedYes, but in TDZ until declaredYes, initialized as undefined
Global declaration becomes a window propertyNoYes
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;

Test yourself

Q1. `let` is scoped to…
Q2. Redeclaring a `let` in the same scope…
Q3. In `for (let i = 0; …)` each iteration…

Discussion

Loading…