Created
February 24, 2017 06:15
-
-
Save ryanbsherrill/0615be397fb5e1c85ce04217f3993512 to your computer and use it in GitHub Desktop.
Scope and the Problem with Globals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Scope refers to the regions of your code in which your variables can be accessed. If a variable is within | |
the global scope, it means that it can be accessed from any other place in your program. If a variable is | |
local to a function, that means that it can only be accessed by the code inside the block of that function. | |
Global variables are avoided because they can cause all kind of unintended side effects. These side | |
effects can cause parts of your program to produce different results when given the exact same inputs, | |
which is obviously not a good thing. | |
Strict mode forces the user to be more careful with their syntax by throwing errors where the code | |
would normally just run. Things such as: if a function parameter name were not unique within whole of the | |
program, you would get a syntax error. | |
Side effects are when a function reaches outside of its own scope and modifies or uses a variable from the | |
global scope. A pure function has no side effects. It runs and uses only what’s in its own scope and has | |
no side effects. | |
Variable hoisting has to do with the way that the JS interpreter parses code. The first thing that it does | |
is go through the program to indentify all variables. This effectively causes all of your variables to be | |
defined before any code is run. It also takes declarations such as: var myVariable = “a variable”; and | |
breaks it up in to two steps —> var myVariable (pushes this to the top of your code) and then | |
myVariable = “a variable”; (happens where you would think it would normally in the code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment