Thinkful 5.4 Scope & the Problem with Globals
//Javascript Scope Study Questions
1) What is scope? Your explanation should include the idea of global vs. local scope.
Scope defines the context for a Javascript variable. In the 'global' scope, the variable
is accessible throughout the script. In the 'local' scope, the variable is only accessible
in the local context where it is declared, such as inside a function.
2) Why are global variables avoided?
Global variables are avoided as a convention of programming norms, but specifically because
global variables can create unintended issues and side effects, making code difficult to
debug and fix.
3) Explain JavaScript's strict mode
'Use strict' enforces the variable declaration convention by using the 'var' keyword, e.g. 'var myVar;'.
'Use strict' prevents variables from being created without the use of the var keyword and will return
an error if variables are created without 'var'.
4) What are side effects, and what is a pure function?
Side effects are what can occur when variables are created in the global scope but then
altered inadvertently by functions or other code using those variables in a local scope. By
definition in this situation, a function becomes 'indeterminate' - meaning the result of the
function is not consistent. 'Pure' functions should be free of side effects and determinate,
meaning they perform their instructions with a consistent result.
5) Explain variable hoisting in JavaScript.
The Javascript interpreter first scans the code before running it, looking for variables
to store into memory. When it runs the script, it 'hoists' the variables to the top. BUT
it only hoists the declaration of the variable - it simply declares it exists (e.g. var myVar;).
It doesn't hoist the assigned values for the variable, which is what can create issues with
variables being undefined if they are created in a different scope.