Skip to content
Closure기술 정리

JavaScript closures: how an inner function keeps its lexical environment

1 min readTech notesMoved from my Tistory blogRead the Korean original

What is a closure?

  • A closure is described as the combination of a function and the Lexical environment in which that function was declared,

and it refers to the JavaScript feature that lets an inner function access the variables of the outer (enclosing) function.

Closure example code

js
let func1 = function(){
    let a = 1;

      let func2 = function (){
        return ++a;
    };
  return func2; //returns the func2 function itself
};

let func3 = func1();
console.log(func3()); // 2
console.log(func3()); // 3

👆 Even when the inner function is called outside the outer function, it can access the outer function's local variables.

That is because it remembers the environment it was created in (Lexical environment).

Source : https://velog.io/@graphicnovel/JS-%ED%81%B4%EB%A1%9C%EC%A0%80%EC%9D%98-%EC%9D%98%EB%AF%B8%EC%99%80-%EC%9B%90%EB%A6%AC-%EC%9D%B4%ED%95%B4-Closure

  • #Closure
  • #JavaScript closure
  • #lexical environment

More in Tech notes