Scope of a variable is its lifetime in the program.

The region of the program in which it can be accessed.

Local Scope

The scope of variable defined via the let and constants defined via the const keyword is between the curly brackets where it's defined - { }.

Accessing such variable or constant outside of it's scope results in exception.

Let's look at the following example:


If we uncomment any of the commented lines, it will result in exception due to accessing variable outside of its scope - the curly brackets.

Global variables

Global variables can be accessed in any scope.

Global variables are defined via the var keyword or without any keyword (such as firstName = "Joe").


In this example hairColor and firstName are defined as global variables. They can be accessed anywhere in the program and are not bound to certain scope.

If we uncomment the last line an exception will be thrown. That's because variables defined via the let keyword and constants are bounc only to the scope in which are defined.