Skip to content

Instantly share code, notes, and snippets.

@bryantee
Created September 14, 2016 23:52
Show Gist options
  • Save bryantee/c43535379db6ab27ddc70c13dfa1dc07 to your computer and use it in GitHub Desktop.
Save bryantee/c43535379db6ab27ddc70c13dfa1dc07 to your computer and use it in GitHub Desktop.
Questions & Answers: Scope and the Problems with Globals

Scope is the set of rules that apply to JavaScript variables regarding how they are declared and accessed. There are two kind of scope: Global scope and Function Scope or Local Scope. The preferred way to declare a variable in Javascript is using the keyword var which keeps the variable from polluting the global scope. A function scope variable is declared in the function and not acccessible to any 'parent scope.' Failing to use var during declaration can lead to unintended consesquences. It can cause bugs and make things more difficult to debug and collaborate on. For instance, a function should, given a set of inputs, always have the same output (a pure function). But this is not necessarily the case when variables cannot be consistently refrenced to (like with multiple functions using a global variable). To get around this, it is wise to use 'strict mode' to prevent your code from compiling if there are any variables not using var.

Hoisting refers to how the JavaScript compiler looks up delcarations in the first pass and creates a namespace before execution. This can explain how function declared using declaration syntax can be called before they're declared. Likewise, variables declared after they're called will result in undefined instead of raising a ReferenceError.

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