Answers for "how to create a closure javascript"

3

closure in javascript

// closure in javascript
-> A closure gives you access to an outer function’s scope
   from an inner function

const outerFun = (a) => {
  let b = 10;
  // inner func can use variable/parameter of outer funcion
  const innerFun = () => {
    let sum = a + b; 
    console.log(sum);
  }
  return innerFun;
}
let inner = outerFun(5);
inner();
Posted by: Guest on September-15-2021
4

closure in javascript

var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };
})();

console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1
Posted by: Guest on January-14-2020
0

JavaScript - Closures

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

//=====
//add5 and add10 are both closures. 
//They share the same function body definition, but store different lexical environments. 
//In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
Posted by: Guest on July-19-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language