Hone

Lessons · TypeScript · let is bounded by its block

Where a variable lives

let and const are limited to the block they are declared in. var leaks out of its block, and reading a let before its line throws.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A var declared in a loop is visible after the loop, and every callback in the loop shares one copy. let gives each iteration its own, which is why modern code never uses var.

How to think about it

const by default, let when you must reassign, var never. If a variable is visible somewhere it should not be, look for a var.

Worked example

if (true) { var v = 1; let l = 2; }
One of each, inside a block.
console.log(v);
1: var leaked out of the block.
console.log(typeof l);
undefined: l lived only inside the braces.
let count = 0;
let can be reassigned.
count = count + 1;
const could not.
console.log(count);
1.

Your turn

A loop counter that belongs to the loop.

for ( i = 0; i < 3; i++) { }

The trap

var in a for loop gives every callback the same final i. let gives each iteration its own copy.

Practise let is bounded by its block on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.