Answers for "what is 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
1

js closure examples

function outer() {
  var counter = 0; // Backpack or Closure
  function incrementCounter() {
    return counter++;
  }
  return incrementCounter;
}

const count = outer();
count(); // 0
count(); // 1
count(); // 2
Posted by: Guest on May-17-2021
1

es6 closures

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

var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value()); /* Alerts 0 */
counter1.increment();
counter1.increment();
alert(counter1.value()); /* Alerts 2 */
counter1.decrement();
alert(counter1.value()); /* Alerts 1 */
alert(counter2.value()); /* Alerts 0 */
Posted by: Guest on February-20-2020
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

A closure Function

var returns_a_func = function () {
  var word = 'I can see inside '     function sentence(){    var word2 = 'I can also see outside. '     console.log(word + 'and ' + word2)   }   return sentence;
}var finalSentence = returns_a_func()finalSentence()
Posted by: Guest on June-22-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language