[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.

    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


    [JS Practice] Functional Addition

    Title :

    Functional Addition


    Create a function add(n) which returns a function that always adds n to any number

    var addOne = add(1);
    addOne(3); // 4
    var addThree = add(3);
    addThree(3); // 6

    Continue reading