SCOPE
Technical Blog
15.APR.2016
What 'scope' is, and how it works in JavaScript.
In JavaScript, ccope is the extent to which a given variable is visible to the rest of the program.
JavaScript has two scopes: global and local. A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program or webpage. A variable that is declared inside a function definition is local and can only be used inside that function.
Imagine a room inside a room. The outer room represents the program as a whole. The inner room represents a function within the program. The inner room has windows which allow people inside the room to look out into the larger outer room. However these windows are one-sided like those windows you see in police interrogation rooms in movies. On one side it acts like a regular window, but on the other it is just a mirror. In this case, though, the windows are reversed. So the people in the inner room can look out into the outer room, but those in the outer room can only see their own reflection when they try to look through into the inner room.
This is a bit how scope works. Variables declared in the outer room, or in the general program, have 'global scope', and are visible to every bit of code in any of the inner rooms. However, variables declared in one of the inner rooms have what's called 'local scope' and when the outer program tries to look at them, they can't, because their view is reflected back at them. There can be as many rooms in a program as one likes even inside each other. So if another room existed inside the inner room, the inner inner room could see all variables in the inner room and outer room but the outer room and inner room would not be able to see any of the variables in the inner inner room. This structure prevents a function from inadvertently altering the rest of the program. It also means that two variables with the same name can simultaneously exist in the program and contain different values.