Andrew's Digital Garden

Block scope in JS

Both let and const are block scoped. They only exist within the innermost block that surrounds them.

function func() { if (true) { let tmp = 123; } console.log(tmp); // ReferenceError: tmp is not defined }

In contrast, var variables are function scoped.

function func() { if (true) { var tmp = 123; } console.log(tmp); // 123 }

This is partly what leads to the classic loop closure bug. [[20210426174851-closure-loops-js]]

[[js]]

Block scope in JS