Closures - TristanVarewijck/Block-Tech GitHub Wiki

What is JavaScript closures?

"Closures in JavaScript is a feature where an inner function has acces to outer functions variables"

So closures can acces three different scope chains:

  1. Has acces to its own scope, the variable defined within its curly braces {}
  2. Has acces to the variables of the outer functions.
  3. Has acces to the global variables.

Code example:

let a = 20; 

function myFunction(){ 
let b = 10; 

function mySecondFunction(){
let c = a + b
return c 
}

return mySecondFunction()
} 

let sum = myFunction() 
console.log(sum) // 30 

The second function has acces to the function where its in and has a global acces thats why this work so well together. and this possible with the JavaScript feature Closure.

Note

return holds a value that you can use later when you want to save or reuse a function that uses return.

Code example:

let firstNumber = 4; 
let secondNumber = 3; 

function add(n1, n2){ 
return n1 + n2; 
} 

const sum = add(firstNumber, secondNumber); 
console.log(sum) // 7;

We made a function with two parameters en saved the calculation to a return statement. At this point this doesn't mean anything because the parameters have no value. But when we save this function to a variable in this case const we also added two different parameters to it with a value. The return statement sees this and now also holds a value that is saved to sum.

Resource