Skip to content

scope and closures

Emily Yu edited this page Apr 3, 2018 · 1 revision

<< back to table of contents

Scope

  • refers to where in your code a given variable or function can be accessed during runtime

Global scope

  • only one global scope throughout a JS document
  • variable is global if it's declared outside of a function
  • globally-scoped variables can be accessed and altered in any other scope

Local scope

  • variable is locally-scoped if it's declared inside a function
  • locally-scoped variables can only be accessed from within the function they are declared in and other functions that may be enclosed within the parent function

Block scope

  • const and let can create block-scoped variables
  • block statement: delimited by pair of curly braces; if and switch conditions, for and while loops
  • block-scoped variables can only be accessed from within the block statement they are declared in

Tips/gotchas

  • never use undeclared variables--you will unintentionally create global variables and clutter up the global scope

Closures

Clone this wiki locally