Skip to content

Instantly share code, notes, and snippets.

@lovubuntu
Created January 17, 2016 06:13
Show Gist options
  • Save lovubuntu/fd74362ba02051babf1f to your computer and use it in GitHub Desktop.
Save lovubuntu/fd74362ba02051babf1f to your computer and use it in GitHub Desktop.

Scope

Lexical Scope

Two forces that can cheat lexical scope:

  1. Eval - By allowing the user to create/modify variables by passing in a string to eval
  2. With - By creating a new variable in the whole new lexical scope (inside the containing function scope)

most of the optimizations the javascript engine does will be pointless if there is eval() or with. So it simply doesn't perform the optimizations at all #long live lexical scope

Function Vs Block scope

Traditional way of thinking -> Write function and then add code to it. Converse -> Wrap any arbitrary section of code and then add a function declaration around it Benefits of this converse

  1. Principle of least knowledge
  2. Collision avoidance
  3. Global namespace -> Libraries avoid collision by using a single object with unique name and gives access to properties
  4. Module Management -> Dependency managers handle namespace issue by using the scope rules

Function Expression (IIFE -> Immediately Invoked Function Expression)

Executes immediately unlike normal function call. The variables and functions inside this function expression will have the scope only inside this function and will not pollute the global namespace.

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