global scope

All variables get global scope if not introduced with "var x" but just with "x = something".

function scope

With the var declaration, variables have function scope (not block scope) and if "var x" appears anywhere in the function, it overrides any global x variable.

Functions defined within functions can also access any variables in the scope of their containing function.

Functions have lexical scope, that is, scope is set up when the function is defined not when it is executed. However, variables in scope can be removed (delete a;) or their values changed while remaining in scope.

  function f(num){
    var fnew = function(){
      return num;
    }
    num * num;
    return fnew;
  }
  var next = f(5);
  next();             => 25
  
closure

Scope can be passed along: when a function returns a function, the returned function has the originating function's scope.

This can be done in two ways:

  function f(){
    var inside = "abc";
    return function(){
      return inside;
    }
  }
  f()();         =>   abc
  or
  new = f();
  new();         =>   abc  
  

or

  var getit;
  function f(){
    var inside = "abc";
    getit = function(){
      return inside;
    }
  }
  f();           => defines getit
  getit();       => abc
  

Another use of closure to hide a value and require that it be accessed only through getter and setter:

  var getValue, setValue;
  (function() {
    var secret = 0;
    getValue = function(){
      return secret;
    };
    setValue = function(v){
      secret = v;
    };
  })()

  getValue();           => 0
  setValue(123);        => returns undefined
  getValue();           => 123
  secret;               => ReferenceError: secret is not defined
  

Or hide an iteration counter:

  function setup(collection) {
    var i = 0;
    return function(){
      return collection[i++];
    };
  }
  
  var next = setup([ 0, 1, 1, 2, 3, 5, 8, 13]);
  next();   => 0
  next();   => 1
  next();   => 1
  next();   => 2
  next();   => 3