Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

closure

function outer() {
  const outerVar = "Hi i am outerVar";
  function inner() {
    const innerVar = "Hi i am innerVar";
    console.log(outerVar);
    console.log(innerVar);
  }
  return inner;
}

const innerFn = outer();
innerFn(); 
// Hi i am outerVar
// Hi i am innerVar
Comment

closure

function makeFunction() {
  const name = 'TK';
  function displayName() {
    console.log(name);
  }
  return displayName;
};
Comment

Closure ()

// Closures
// In JavaScript, closure is one of the widely discussed and important concepts.
// A closure is a function that has access to the variable from another function’s scope which is accomplished by creating a function inside a function. As defined on MDN:
// “Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created.”
// In JavaScript, closures are created every time a function is created, at function creation time. Most JavaScript developers use closure consciously or unconsciously — but knowing closure provides better control over the code when using them.
// Example:

function Spellname(name) {
var greet = "Hi, " + name + "!";
var sName = function() {
var welc = greet + " Good Morning!";
console.log(greet);
};
return sName;
}
var Myname = SpellName("Nishi");
Myname();  // Hi, Nishi. Good Morning!

// In the above example, the function sName() is closure; it has its own local scope (with variable welc) and also has access to the outer function’s scope. After the execution of Spellname(), the scope will not be destroyed and the function sName() will still have access to it.

Comment

what are closures

Closures are related and often confused with lambda functions.
The 2 concepts are wonderfully explained and distinguished 
in this StackOverflow answer :
https://stackoverflow.com/a/36878651/13574304
Comment

closure

var counter = (function() {  //exposed function references private state (the outer function’s scope / lexical environment) after outer returns. 
 var privateCounter = 0;
 function changeBy(val)   { privateCounter += val; }
 return {  increment: function() {changeBy(1); },
           decrement: function() {changeBy(-1);},
           value: function() {return privateCounter; }
  };
})();

counter.increment(); counter.increment();
counter.decrement();
counter.value();      //  1
Comment

closures

// Closures
//Almost mystical like feature that many developers fail to fully understand.
//We cannot create closures manually like how we create arrays and functions.
//Rather closures happen in certain  situations. We just need to recognize 
//those situations.

//Example:
const secureBooking = function () {
   let passengerCount = 0; //Variable of the secureBooking Function
   
  //returns a function
   return function () {
     passengerCount++; //Adding to the passengerCount
     console.log(passengerCount);
  };
 };

const book = secureBooking(); //capture that function
book();

//In the above example we have a function called secureBooking
//That function returns another function, which we stored in book variable
//We then call the book() function and it adds to the passengerCount.
//But you may be wondering? How can it add to the passengerCount
//if the secureBooking has finished executing, shouldn't it not exist?
//This works because all functions have access to the variable environment
// in which they were created in. Meaning since secureBooking created
// the function which we stored in book. The book function now has 
// access to the variable environment of secureBooking function.
Comment

Closure Example


	 function Counter() {
    var counter = 0;
alert("XXXXX");
function increaseCounter()
{
return counter +=1;
} 

return increaseCounter;
}

/***/
const counter = new Counter();
console.log(counter());
console.log(counter());


/*note that alert("XXXX") only executes once*/
/*think of counter() = new Counter() declaration as storing the value of ONE Counter function execution and 
the remaining times you use counter(), you reexecute only the returned function*/
/*use counter() instead of Counter() if you want alert("XXXX") to execute only once AND for you to be able to return an actual value otherwise you only console.log a function and alert executes multiple times*/
Comment

what is closure

outer = function() {
  var a = 1;
  var inner = function() {
    console.log(a);
  }
  return inner; // this returns a function
}

var fnc = outer(); // execute outer to get inner 
fnc();
Comment

closure

func main() {
  x := 0
  increment := func() int {
    x++
    return x
  }
  fmt.Println(increment())
  fmt.Println(increment())
}
Comment

closure

function add(a) {
     return function(b) {
         return a + b;
     };
 }

 let addTen = add(10);
 let addSeven = addTen(7);

 console.log(addSeven); // 17
Comment

closure

def say():
    greeting = 'Hello'

    def display():
        print(greeting)

    display()
Code language: Python (python)
Comment

closure examples

function makeFunc() {
  const name = 'Mozilla';
  function displayName() {
    console.log(name);
  }
  return displayName;
}

const myFunc = makeFunc();
myFunc();
Comment

closure example

const add = (function () {
  let counter = 0;
  return function () {counter += 1; return counter}
})();

add();
add();
add();

// the counter is now 3
Comment

PREVIOUS NEXT
Code Example
Javascript :: clear dict javascript 
Javascript :: write files in Node.js 
Javascript :: js key event 
Javascript :: convert text to qr code in angular 
Javascript :: how ot send user agent in nodejs https header 
Javascript :: form handling in react 
Javascript :: how to name a javascript variable 
Javascript :: object assign in javascript 
Javascript :: obtener primer elemento de un array javascript 
Javascript :: express get raw query 
Javascript :: how can I send form data with image in angular 
Javascript :: jquery pass $ 
Javascript :: vue js set array value by key 
Javascript :: omit key from object js 
Javascript :: launch.json 
Javascript :: recaptcha v3 js 
Javascript :: push method in javascript 
Javascript :: reactstrap search bar 
Javascript :: How to include route handlers in multiple files in Express 
Javascript :: how to add attribute in a element 
Javascript :: undefined 
Javascript :: array within array javascript 
Javascript :: react array if id is present do not add element 
Javascript :: update reducer 
Javascript :: progress bar loading ajax 
Javascript :: fibonacci sequence javascript 
Javascript :: Passing a state as a prop in react 
Javascript :: javascript compare dates 
Javascript :: javascript await keyword 
Javascript :: circular queue in javascript 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =