// Зоны видимости
You can think of scope like the view of the night sky from your window. Everyone who lives on the planet Earth is in the global scope of the stars. The stars are accessible globally. Meanwhile, if you live in a city, you may see the city skyline or the river. The skyline and river are only accessible locally in your city, but you can still see the stars that are available globally.
Blocks and Scope
We’ve seen blocks used before in functions and if statements. A block is the code found inside a set of curly braces {}. Blocks help us group one or more statements together and serve as an important structural marker for our code.
Global Scope
In global scope, variables are declared outside of blocks. These variables are called global variables. Because global variables are not bound inside a block, they can be accessed by any code in the program, including code in blocks.
While it’s important to know what global scope is, it’s best practice to not define variables in the global scope.
Block Scope
When a variable is defined inside a block, it is only accessible to the code within the curly braces {}. We say that variable has block scope because it is only accessible to the lines of code within that block.
Variables that are declared with block scope are known as local variables because they are only available to the code that is part of the same block.
Scope Pollution
When you declare global variables, they go to the global namespace. The global namespace allows the variables to be accessible from anywhere in the program.
Scope pollution is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents.
While it’s important to know what global scope is, it’s best practice to not define variables in the global scope.
Practice Good Scoping
Tightly scoping your variables will greatly improve your code in several ways:
- It will make your code more legible since the blocks will organize your code into discrete sections.
- It makes your code more understandable since it clarifies which variables are associated with different parts of the program rather than having to keep track of them line after line!
- It’s easier to maintain your code, since your code will be modular.
- It will save memory in your code because it will cease to exist after the block finishes running.