Skip to content

Instantly share code, notes, and snippets.

@Schmerb
Created April 23, 2017 01:12
Show Gist options
  • Save Schmerb/d96991868f3f5892c7e39a4d35b3d28a to your computer and use it in GitHub Desktop.
Save Schmerb/d96991868f3f5892c7e39a4d35b3d28a to your computer and use it in GitHub Desktop.
Brief rundown of scope in JavaScript.
What is scope?
Scope refers to the part of your program / source code that a given variable can 'see'. In other words,
scope defines which variables (and specific values) functions or variables both within and outside of
functions have access to. There are two distinct types of scope, global (also known as 'window' scope)
and local scope.
The global scope consists of the entire source file and can even stretch across multiple
files given those files are loaded properly into an html file. Global variables are accessible from anywhere
within the file(s) including inside of functions or nested-functions. The local scope refers to variables
that have been declared inside of a function (nested-function) and thus only those variables can be accessed
by other variables or functions within the same part of the code. Thus, a variable defined locally inside of one
function is basically invisible to any code outside of that function (parent scope(s)).
Why do we avoid global variables?
We avoid global variables because of the possibility that someplace else in your code, you may reference said
variable and manipulate it (overwrite it) unknowingly and cause trouble.
JavaScript 'strict mode'
By including 'use strict'; at the top of every JS file, we are telling the interpreter that we do not want
any global variables defined and do not have to worry about accidentally forgetting to explicitly label a variable
with the var keyword, thus creating unwanted global variables that other parts of code / files may end up manipulating.
With this feature enabled, if any variables are declared without the 'var' keyword then an 'UncaughtReferenceError'
is thrown.
Side effects are when a function gains access to and changes the value of a variable that exists outside
of its local scope.
A pure function is one that is both determinate and has no side effects. i.e. given the same input, the output will
always be the same and it does not manipulate the value of any variable existing outside of its own scope.
Hoisting
Unlike other paradigms, JavaScript, upon interpretaion of the source code, makes an inital 'sweep' of the file
in order to create memory for variable and function declarations. It moves these declarations to the top of
their respected scope regardless of where they actually occur in the source file. Because of this functionality,
at run-time it is possible to execute a method / function call before that function has actually been defined
thanks to the 'pre-processing' that takes place.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment