Skip to content

Instantly share code, notes, and snippets.

@Manny1806
Last active April 1, 2018 22:52
Show Gist options
  • Save Manny1806/e4dd9c0b5db69908401ce2218bf0877e to your computer and use it in GitHub Desktop.
Save Manny1806/e4dd9c0b5db69908401ce2218bf0877e to your computer and use it in GitHub Desktop.
Scope questions
1. Scope refers to the accessibility of a variable. If a variable is created outside of a function its scope is considered
to be global which means it can be accessed by any function in the javascript file. Global variables can even be accessed
by other linked Javascript files as long as the file with the global variable is loaded first. Variables that are created
in a function are considered to have local scope which means they can only be accessed within the function they were created
in. When a local scope variable is created that has the same as a global scope variable, the local variable will take
precedence over the global variable and not affect the global variable.
2. Global variables are avoided in Javascript because they can lead to unintended results. When more than one function uses
or alters a global variable it risks the outcome of the functions being not what is expected. One function might assume
a global variable has a certain value when in fact another function has altered the global variable's value. If this happens
and a program has many functions it can be difficult to pin point where the problem is.
3. When strict mode is enabled in Javascript, any time a variable is declared without using the let or const keyword an error
is thrown by the program. The purpose of this is to prevent any unintentional changes to global variables by fuctions.
Strict mode can be enabled by adding 'use strict'; to the top of a Javascript file or if it is only needed for a particular
function it can be added to the top of that particular function.
4. Side effects are when a function alters a variable that is outside its local scope. A pure function is a function that will
always have the same results when given the same inputs. Therefore a pure function will never have side effects.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment