Answers for "What is a closure in JS"

1

closure in javascript

function OuterFunction() {

    var outerVariable = 1;

    function InnerFunction() {
        alert(outerVariable);
    }

    InnerFunction();
}
Posted by: Guest on May-04-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

what is a closure in javascript

//Closures are the inner functions that are embedded in parent function
function getName(){
    // print name function is the closure since it is child function of getName
     function printName(){
         return 'Kevin'
     }
     // return our function definition
     return printName;
}

const checkNames = getName();
console.log(checkNames());
Posted by: Guest on August-07-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language