Closure in JavaScript – Part 1: Lexical Environment

Tram Ho

Hello guys, lately I’m still searching for Javascript of things, having read through the closure section. To understand closures, we first need to know what a Lexical Environment is, so let’s find out.

1. Definitions

All functions or code blocks in JavaScript and the Global Object have an anonymous object, called the Lexical Environment . A Lexical Environment has 2 parts:

  1. Environment Record : an object that contains all the local variables as its property and some other information (like the value of this ).
  2. A reference (treat it as a link) to the external Lexical Environment .

2. Variables

It can be said that a variable in Javascript (variable) is a property of the Environment Record of that environment. When you are accessing or modifying a variable, it means you are accessing or modifying that property of the Environment Record .

For example:

In this example, the phrase variable will be a property of the Environment Record object attached to the Global Object.

  • Note: Lexical Environment only exists as specs, it is theoretically only available. There is no way to get this object and change it.

3. Function Declarations

When you declare a function in Javascript, that function also becomes a method of Environment Record in that scope. However, when you declare a function, the function is immediately available, even before you declare the function.

4. Inner and Outer Lexical Environment

When a function is run, at the beginning of the process, a new Lexical Environment is created to hold variables and parameters.

For example:

  • Lexical Environment inner Lexical Environment (of the say function) has an attribute of name , which is the parameter passed. When calling this function with say('Alice') , the value of name is Alice
  • Lexical Environment outside the say function (of the Global Object) contains the phrase property and also the say function.
  • Note: when the program wants to find a variable, it will look from the Lexical Environment inside out until it finds the Lexical Environment of the Global Object. In the above example, the program did not find the phrase variable in Lexical Environment inside the say function so it looked outside.

Those are the basics of Lexical Environment, we will come back to Closure in the next section. You can read more here .

Share the news now

Source : Viblo