Skip to content

Closures

SimonPlanje edited this page Jun 20, 2020 · 4 revisions

Closures

We did already use closures without even noticing. When you create a function inside a function, you have created a closure. The inner function is the closure.

Simple example of closure

fucntion simon(){  
hallo();` 👍   
function hallo(){  
}  
}  
hallo(); 👎   

hallo() is not available to call outside of the function simon() because hallo() becomes a local variable/function.

little more complicated example of closure

makeName(' simon');  
makeName(' kees');  

function makeName(name) {  
  delcareName(name);  
  function delcareName() {  
    console.log('hallo' + name);  
  }  
}  

Closure normally always takes the last updated value of the variable, but in the example above because of the function inside a function, two values get console logged. This is a nice example of the power of closures.

Another great example from freecodecamp:

function outside(num) {  
  var rememberedVar = num; // In this example, `rememberedVar` is the lexical environment that the closure 'remembers'  
  return function inside() { // This is the function which the closure 'remembers'
    console.log(rememberedVar)  
  }  
}  
var remember1 = outside(7); // remember1 is now a closure which contains `rememberedVar = 7` in its lexical environment and //the function 'inside'  
var remember2 = outside(9); // remember2 is now a closure which contains `rememberedVar = 9` in its lexical environment, and //the function 'inside'  

remember1(); // This now executes the function 'inside' which console.logs(rememberedVar) => 7  
remember2(); // This now executes the function 'inside' which console.logs(rememberedVar) => 9   

Sources

https://css-tricks.com/javascript-scope-closures/
https://www.youtube.com/watch?v=3a0I8ICR1Vg
https://www.youtube.com/watch?v=-jysK0nlz7A
https://www.freecodecamp.org/news/closures-in-javascript-explained-with-examples/

Clone this wiki locally