DEV Community

Cover image for Scopes in Javascript
Juan de Tomaso
Juan de Tomaso

Posted on

3

Scopes in Javascript

In this post I want to explore the scopes in Javascript making a parallelism between Javascript and the principles of federalism in political science.
Alt Text
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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs