Answers for "what are closures"

1

what is closure in javascript

function OuterFunction() {

    var outerVariable = 100;

    function InnerFunction() {
        alert(outerVariable);
    }

    return InnerFunction;
}
var innerFunc = OuterFunction();
Posted by: Guest on May-25-2021
0

What is Closures in JavaScript

/*A closure is the combination of a function bundled together (enclosed) with references
to its surrounding state (the lexical environment). In other words, a closure gives you 
access to an outer function’s scope from an inner function. In JavaScript, closures are 
created every time a function is created, at function creation time.*/

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();
Posted by: Guest on September-25-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

syntax of closures

/*
{ (parameters) -> return type in
body
}
*/

var numbers = [1, 2, 3, 4]

var reversed = numbers.sorted(by: {(a: Int, b: Int) -> Bool in
    return a > b
})
Posted by: Guest on September-05-2021
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
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