[Javascript] Closure

Found a very good article in Chinese from the blog of Ruanyifeng which talking about the closure of javascript.

Before learning closure, it is better to understand the variable scope.

Learn by doing (all examples with # have been tested, try them):

  • #1 example
  • Global variable :

    var v1 = 1;
    function f1() {
      console.log(v1); // Display 1 in console
    }
    
  • #2 example
  • Local variable :

    function f2() {
      var v2 = 1;
    }
    console.log(v2); // Can't find variable:v2
    

    So local variable cannot be used outside of a function.

    Attention!
    There is an exception, local variable defined in function must use the “var” command, or it will be considered as a global variable, see an example:

  • #3 example
  • function f3() {
      v3 = 1;
    }
    f3(); // call function f3, the variable will be initialized 
    console.log(v3); // Display 1 in console
    

    Continue reading