It provides encapsulation (keep variables confined), avoids naming collisions, lets the engine free memory when the block ends, and fixes the classic var loop closure bug by giving each iteration a fresh binding.
What Is Block Scope in JavaScript?
Why is block scope important in JavaScript?
The answer
More FAQs in What Is Block Scope in JavaScript?
Variables declared with let and const inside a pair of braces are only accessible inside those braces. var is not block-scoped; it is function-scoped and leaks out of blocks.
Any code wrapped in a pair of braces {}. Blocks appear in if statements, for and while loops, try...catch, and as standalone blocks. let and const declared inside any of these are block-scoped.
Yes. var is function-scoped, not block-scoped. A var inside an if or a standalone block is hoisted to the enclosing function or global scope. let and const do not leak.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.