Answers for "when to use closures in 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

js closure

// global scope
var e = 10;
function sum(a){
  return function(b){
    return function(c){
      // outer functions scope
      return function(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}

console.log(sum(1)(2)(3)(4)); // log 20

// You can also write without anonymous functions:

// global scope
var e = 10;
function sum(a){
  return function sum2(b){
    return function sum3(c){
      // outer functions scope
      return function sum4(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}

var sum2 = sum(1);
var sum3 = sum2(2);
var sum4 = sum3(3);
var result = sum4(4);
console.log(result) //log 20
Posted by: Guest on July-12-2021

Code answers related to "when to use closures in javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language