Scope in JavaScript:


Scope refers to where variables and functions are accessible, and in what context it is being executed. Basically, a variable or function can be defined in a global or local scope. Variables have so-called function scope, and functions have the same scope as variables.

In the picture below, the scope of the local variable is highlighted blue – it's the function where that var was defined. Any code inside that function can access (read and change) this variable. Any code outside it can't. It's local, so it's invisible from outside.


...

Variables defined in the white area are global. Their scope is the entire script. Which means that you can read and change them anywhere in your code.

To make things clear let’s use a simple metaphor. Every country in our world has frontiers. Everything inside these frontiers belongs to the country’s scope. In every country there are many cities, and each one of them has its own city’s scope. The countries and cities are just like JavaScript functions – they have their local scopes. The same is true for the continents. Although they are huge in size they also can be defined as locales. On the other hand, the world’s oceans can’t be defined as having local scope, because it actually wraps all local objects – continents, countries, and cities – and thus, its scope is defined as global.