Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save liseferguson/3f3e6fae077c069c11915ffe34695356 to your computer and use it in GitHub Desktop.
Save liseferguson/3f3e6fae077c069c11915ffe34695356 to your computer and use it in GitHub Desktop.
Challenge: In your own words
1.) What is scope? Your explanation should include the idea of global vs. local scope.
Scope is the extent of the area in the code where a piece of code can behave or be accessed. How the code is executed depends on where the variables are defined within the scope chain. Global scope is when a variable is defined outside of a function. This means it can be used anywhere in the code, therefore it is global. Local scope is when a variable is defined inside of the function, and can therefore only be executed within that code's block of instructions. Outside of the function it is defined inside, it ceases to exist, and the code will try to access variables in the parent code, and eventaully the global scope.
2.) Why are global variables avoided?
Global variables can be accessed anywhere in the code and even across files, but they can also be altered in unintended ways. If the code has undefined variables, for instance, it will search through the scope chain until it finds a variable to use, and sicne the global variable is so accessible, it will often use this and alter it. The altered global variable will be used in any other piece of code that calls on it, which will break the function's intended action and produce wayward results. Using globals can be messy and, in longer pieces of code with many functions, it can create a chain of errors which can be time-consuming to track down the root of.
3.) Explain JavaScript's strict mode.
Setting 'use strict;' at the top of your js file will trigger an error message if you accidentally create a global variable. This prevents the programmer from continuing to write problematic global variables into their code and then having to go back later to fix all the bugs those globals likely create.
4.) What are side effects, and what is a pure function?
Side effects are outcomes of running a code that is set up without a solid foundation, so that the code will behave unpredictably and inconsistently. Using global variables often results in side effects in the code, because global variables are able to be altereed if there are undefined variables in the local code. For example, if a local function has undefined variable, the code will look to the parent scope for the variable, and will create one if there is none. A code is pure when it is produces the same results every time given the same values (aka it is "determinate"), and produces no side effects.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment