In this post I want to explore the scopes in Javascript making a parallelism between Javascript and the principles of federalism in political science.
Let's say that the scope of variables are defined in a similar way to how a jurisdiction works in a federal system such as the one in Argentina or the United States: the global sphere (let's say the National State) sanctions laws that rule over all the sub-national states. Furthermore, the sub-national states dictate laws that rule over their territory, and so on, the counties or interior departments sanction laws that rule over their jurisdictions.
Hence, the scope of the laws rules from top to bottom (National -> State -> County) and not the other way around. A county regulations has no authority at the state level, and a state regulation has no authority at the national level.
The scope of variables in Javascript works the same way: a bind defined at the most global level has “jurisdiction” over the whole program. And so, a bind declared in a function has no global reach. It only has “jurisdiction” within the scope of the function in which it was defined and in functions nested within it. A variable defined in a nested function within another function only has jurisdiction in the scope of the nested function where it was defined, but has no reference in external functions or scopes, just like a county regulation has no authority at the state level.
Finally, it is important to note that the parallelism only occurs when the variables are defined with let or const words. When the variables are defined with the word var it is necessary to look for another scenery because they are visible throughout the whole program, no matter where exactly they are defined.
Hope you find it intresting and useful.
Top comments (0)