Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williams-Christopher/e95d2a56e9e2c032b0dfaf7f67b6f708 to your computer and use it in GitHub Desktop.
Save Williams-Christopher/e95d2a56e9e2c032b0dfaf7f67b6f708 to your computer and use it in GitHub Desktop.
Module 5 - Checkpoint 10 - Variable Scope
What is scope? Your explanation should include the idea of global vs. block scope.
Why are global variables avoided?
Explain JavaScript's strict mode
What are side effects, and what is a pure function?
Scope is an important concept in programming and it refers to where a variable is valid in code and which bits of code can modify its value. With JavaScript, a variable can be valid in the global or block scopes. A variable with global scope is one that is defined outside of a function. Because of this, its value is accessible (and therefore mutable) from anywhere within the JavaScript file where it is defined as well as any other JavaScript files loaded after it. Conversely, a variable declared inside of a function is said to have a block scope and it is only accessible to the code block of that function. It is wise to avoid global variables because they can quickly lead to hard to squash bugs, unintended side effects, and do not support the idea of pure functions.
Side effects are changes to an application state that a function makes outside of its scope. A pure function would avoid this, accepting a parameter and returning a value, modifying no data outside of its scope. Some side effects are intended, writing a list of names to a text file for example. An unintended side effect could occur when misusing variable scope, perhaps creating a variable inside a function without the let or const keywords, allowing the JavaScript interpreter to step up the scope chain and create a global variable. This last situation can be avoided with good program practices, part of which would be to enter the 'use strict' directive at the top of a JavaScript file. This directive causes the interpreter to throw an error when encountering an undeclared variable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment