Answers for "example of closures in javascript"

1

closures in javascript

// A closure is a function having access to the parent scope, 
// even after the parent function has popped.

function greeting() {
    let message = 'Hi';

    function sayHi() {
        console.log(message);
    }

    return sayHi;
}
let hi = greeting();
hi(); // still can access the message variable
Posted by: Guest on February-01-2022
1

closure in javascript

-->closure in javascript
//closure is the combination of function and the lexical enviornment in
//which the function is defined.closure give you access to the functions
//and variables outside the function.
function outer(){
  const outerData ="outer";
  function inner(){
    const innerData="inner";
    console.log(`${outerData} and{innerData}`);
  }
  inner();
}
outer();
Posted by: Guest on December-22-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

Code answers related to "Javascript"

Browse Popular Code Answers by Language