Skip to content

Instantly share code, notes, and snippets.

@jhwheeler
Last active January 7, 2017 13:09
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 jhwheeler/85b835c57332edbfc922f7e0796c3fa8 to your computer and use it in GitHub Desktop.
Save jhwheeler/85b835c57332edbfc922f7e0796c3fa8 to your computer and use it in GitHub Desktop.

In Your Own Words: Scope

What is scope?

Scope is the part or section of a program to which a given function, variable, or object has access. Global scope is accessible by any and all functions, while local scope is only accessible to the encasing function and any function(s) inside said encasing function.

Why are global variables avoided?

Global variabes are to be avoided for various reasons. One being they pollute the namespace, i.e. you may use a global variable accidentally when intending to use a local one. They are also difficult to track: similarly to the point above, you may forget about the global variable if your program gets very large and accidentally modify it without intending to. Furthermore, they make it more likely to have unintended side effects pop up in your code, creating a codebase that is difficult to test, debug, and develop.

Explain Javascript's strict mode.

ES5's strict mode enforces different syntactical structures that are more limiting and constraining, providing the developer with certain checks and balances (so to speak) when writing a program. For example, when one accidentally creates a global variable, a ReferenceError is thrown; in addition, other types of mistakes or bugs will throw errors instead of silently failing.

In addition to various other functionalities, strict mode also reserves keywords that are in the next version of ES, so that the transition from one to the next is easier.

What are side effects and what is a pure function?

Side effects occur when a function, usually by accessing the global scope, modifies variables declared elsewhere. This can lead to unpredictable behavior and hard-to-test code.

Pure functions have no side effects; furthermore, they are completely determinate, i.e. what you see is what you get. Every time a pure function runs with a given input, it will produce the same output.

Explain variable hoisting in Javascript.

Because the engine first stores all of the variable declarations on its first pass through the code -- and then only in the second pass through stores the assignments thereof -- variables declared after they are called are hoisted above their callsite and are interpreted as such.

e.g.

foo() function foo() { console.log("foo!") } The above code will run as if it were written with the callsite below the function declaration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment