Scope, hoisting, event loop: Block scope

There is a very important difference between declaring a variable using var, or declaring it with let or const.

A variable defined as var inside a function is only visible inside that function, just like function parameters.

That’s it.

But a variable defined as const or let has an additional feature.

It is only visible inside the block where it is defined.

What is a block? A block is anything identified by a pair of curly braces.

Like a function, sure, and in this case there’s no difference from var (except for hoisting as we’ll later see).

But a block can also be a loop, or an if/else:

count = 12
if (count > 10) {
  let text = "Bigger than 10!"
  console.log(text)
}

console.log(text)

In the above example, text will give a ReferenceError: text is not defined error.

Try changing its declaration inside the if to var text, and you will see its value even outside of the if.

Again, it’s a matter of encapsulation, and this is one of the reasons why you should generally prefer, in my opinion, let and const declarations over var.

Lessons in this unit:

0: Introduction
1: Global scope
2: Function scope
3: ▶︎ Block scope
4: Shadowing
5: Hoisting
6: Closures
7: An issue with `var` variables and loops
8: The event loop