Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdesire/ea301c4d8a93af6b875e307de8595f94 to your computer and use it in GitHub Desktop.
Save tdesire/ea301c4d8a93af6b875e307de8595f94 to your computer and use it in GitHub Desktop.
Variable scope defines where a variable can be accessed and modified within a body of code.
Scope typically falls into two categories: global scope and block scope.
A variable with global scope is one that has been declared outside the body (block) of a particular function. It is considered global
because it can be accessed and modified anywhere within the code, including within the body of a function.
In contrast, a variable with block scope is one that has been declared within a function's instruction block (delineated by {} brackets),
and can thus only be accessed and/or modified within that function's body.
It is considered programming best-practice to avoid the use of global variables because of their universal mutability. By that I mean,
it is possible for programmers to modify the value of a global variable from within a function's (local) instruction block.
This phenomenon, known as a side-effect, can have dire consequences when executed unintentionally, given that it can lead to
inconsistencies in a code's output.
When a code, given a single set of inputs, produces varied outputs, it is considered indeterminate -- referring to the progammer's inability
to determine the outcome of particular set of code.
Hence, programmers strive to produce pure code, or code that is both determinate and has no side-effects. Code that is pure is more likely
to efficiently complete it's intended function, and is less susceptible to errors or bugs.
An effective way to avoid indeterminate code is the use of the strict mode command ('use strict';), which when implemented raises an error
whenever variables are declared without the 'let' or 'const' declaration markers. This will prevent a programmer from writing lines of
code that produce side-effects (in which global variables are modified locally).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment