Web Development · Notes


Sat, 30 Sep 2023 10:57:04 GMT
JavaScript closure

function outside(x) {
    function inside(y) {
        return x + y;
    };
    return inside;
}

fn_inside = outside(5);
result = fn_inside(3); // 8
result = fn_inside(5); // 10
result = fn_inside(8); // 13

function makeCounter() {
  let count = 0;
  return function() {
    return count++;
  };
}

let counter1 = makeCounter();
let counter2 = makeCounter();

alert( counter1() ); // 0
alert( counter1() ); // 1

alert( counter2() ); // 0 (independent)