Created
August 11, 2018 19:22
-
-
Save rjwilliams87/ea5cac35041f5332e6d8b7d18ae65410 to your computer and use it in GitHub Desktop.
Thinkful Q/A on scope
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
What is scope? | |
Scope defines how the variables declared in a program can be accessed at different places in the code. Any variable | |
declared outside of a function has a globlal scope. Variables declared within the function block have block scope. If a variable | |
has global scope it is accessible throughout the code by any function. Global variables may lead to unexpected side effects | |
making functions indeterminate, thus it is best to avoid using them. Variables with block scope are accessible only within the function | |
block in which they are defined, and thus have no effects on variables outside of their scope. | |
Why are global variables avoided? | |
Global variables can lead to unintended side effects and indeterminate functions. JavaScript uses the scope chain to find the value of | |
a variable once it is called inside of a function. If the variable is not defined within the function it will reach to the global level | |
to find the value of the variable. If the function calls for the variable to be altered, it will be done so globally. Altering gloabal | |
variables can lead to collision with other parts of the code that rely on the same global variable. | |
It is best practice to keep a function pure and determinate. This is not possible when functions must rely on global variables. It is | |
best to avoid using them, because they can lead to hard-to-track-down bugs in the code. | |
Explain JavaScript's strict mode. | |
JavaScript uses the strict mode to catch common coding errors when writing the code. By using strict mode JavaScript will disable certain | |
features and throw an error in cases when variables are improperly declared. Strict mode prevents the programmer from accidentally | |
creating global variables, and thus makes code more secure. | |
What are side effects, and what is a pure function? | |
A side effect is when a function reaches out of its local scope into the global scope and alters variable(s) globally. This causes | |
unintended effects on the program as a whole, since other code within the program may rely on the same variable. This leads to functions | |
that are indeterminate. By declaring variables in the function block, functions are kept pure. That is to say, that is to say that it | |
has no side effects and is determinate, meaning that given the same inputs at various places within the code it will always return the | |
same thing. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment