Closures
Jun 13, 2021
Almost every Javascript interview will ask you what a closure is
For some reason, the definition of closure doesn’t seem to stick with me well. What is so closed about being able to access the variables inside your curly braces, the parent scope, as well as the global? I keep on having to look it up. But this is what I gather:
Closures are particular to Javascript. You will see them used more often with functions within functions.
function outer() {
const a = 23;
function inner() {
console.log(a);
}
inner();
}outer();
//=> 23// The `inner` function is said to have closure over the variable `a`
It all has to do with scope and what is accessible within functions. Function inner() has access to constant a which is 23.