Thursday, April 18, 2019

JavaScript(5)--- Scope

Scope

    Scope defines where variables can be accessed or referenced. 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.
  1. 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.

Block Scope

The next context we’ll cover is 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

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.

What I learned in this lesson...
What I'll be doing tomorrow?
I'll be learning about Arrays.

No comments:

Post a Comment