Guest User

Untitled

a guest
May 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. # Scope
  2.  
  3. ## What is scope?
  4. Scope is the set of rules governing where a variable is valid based on the location of its definition.
  5.  
  6. Scope can be Global or Local. Any variable defined outside a function (or without the use of `let` or `const`)has a _global scope_ and is accessible from anywhere in the program. A variable defined inside a function has a _local scope_ and is only accessible from the context in which it was defined or blocks/functions nested within that context. This concept of nesting scope is referred to as the _Scope Chain_. Local scope will over-ride global scope. So, a variable defined with local scope can have the same name as a variable with global scope, but the program will treat them as separate variables. The value contained in the variable can't rise above where it was defined in the scope chain. Once the program rises out of the local scope, the code will look for a definition in the new scope and will keep looking in progressively higher parent scopes until it finds one. If the code works up the scope chain to global scope without finding a definition, it will raise an `Uncaught ReferenceError`.
  7.  
  8. ## Why are global variables avoided?
  9. Global variables are avoided because they have a tendency to create unintended side effects. When global variables are used and cause unitended side effects, the code easily becomes _indeterminate_. Indeterminate functions will produce different results at different times when given the same inputs. They cannot be trusted and lead to bugs in the code. When functions reliably produce the same result when given the same inputs, they are _determinate_.
  10.  
  11. ## Explain JavaScript's strict mode
  12. _Strict Mode_ in JavaScript enforces the use of `let` or `const` when defining variables. Any variables declared without using one of those two keywords will trigger an `Uncaught ReferenceError`. Strict mode is enables by writing `'use strict';` either at the top of a file (to enforce strict mode for the whole file) or at the top of a function (to enforce strict mode only within the function body).
  13.  
  14. ## What are side effects, and what is a pure function?
  15. _Side effects_ are when functions change a value in the code outside their own parent scope. This can be good when that is the intended use of the function (like saving a record to a database.) _Pure functions_ are functions that are both determinate and have no side effects: they always return the same value given the same input(s) and they don't change anything outside their parent scope.
Add Comment
Please, Sign In to add comment