Skip to content

Instantly share code, notes, and snippets.

@hartleybrody
hartleybrody / Javascript Variable Scoping.md
Last active February 3, 2019 19:13
Variable scoping in Javascript can be confusing so I set out to make notes of the basic rules so that I can reference them later. Hope these are useful to others, happy to talk pull requests for corrections.

Javascript has two kinds of scope:

  1. Local (inside a function)
  2. Global (outside a function)

The var Keyword

  • Using the var keywords creates the variable in the current scope
    • If the current scope is global, then var is unnecessary (see below)
    • If the current scope is local, then you’re creating a local variable in the current scope
  • If you don’t use var, then Javascript goes up the “scope chain” to see if it’s already been declared