Skip to content

Instantly share code, notes, and snippets.

@ganny26
Last active December 8, 2020 09:32
Show Gist options
  • Save ganny26/04654399a33562c43eca2c7523caa273 to your computer and use it in GitHub Desktop.
Save ganny26/04654399a33562c43eca2c7523caa273 to your computer and use it in GitHub Desktop.
Closures.md

To know more bout execution context and lexical environment read here

Used in higher order functions read here

Closure

Example 1

var counter = (function() {
    var count = 0;
    function increment() {
        count += 1;
    }
    return {
        increment: function() {
            increment(1);
        },
        getValue: function() {
            return count;
        }
    }
})();

Example 2

function multiplier(num){
	return function (multiplier){
		return num * multiplier
	}
}

var double = multiplier(2)
var triple = multiplier(3)

double(3) // 6
triple(3) // 9

Example 3

//module

function Student(_name,_marks) {
  var username = _name;
  var marks = _marks;

  function get_user() {
    console.log(username);
  }

  function calculate_marks() {
    console.log(marks.reduce((all, item) => (all += item)));
  }

  return {
    get_user: get_user,
    calculate_marks: calculate_marks
  };
}

var s1 = Student('s1',[10,20,30]);

s1.get_user(); // s1
s1.calculate_marks(); // 60

Memoization

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