# Closure JavaScript is a very function-oriented language, it gives a lot of freedom. A function can be created at one moment, then passed as a value to another variable or function and called from a totally different place much later. We know that a function can access variables outside of it. And this feature is used quite often. But what happens when outer variables change? Does a function get a new value or the old one? Also, what happens when a variable with the function travels to another place of the code and is called from there -- will it get access to outer variables in the new place? There is no general programming answer for these questions. Different languages behave differently. Here we'll cover JavaScript. [cut] ## A couple of questions Let's formulate two questions for the seed, and then study internal mechanics piece-by-piece, so that you will be able to answer them and have no problems with more complex ones in the future. 1. The function `sayHi` uses an external variable `name`. The variable changes before function runs. Will it pick up a new variant? ```js let name = "John"; function sayHi() { alert("Hi, " + name); } name = "Pete"; *!* sayHi(); // what will it show: "John" or "Pete"? */!* ``` Such situations are common in both browser and server-side development. A function may be scheduled to execute later than it is created: on user action or after a network request etc. So, the the question is: does it pick up latest changes? 2. The function `makeWorker` makes another function and returns it. That new function can be called from somewhere else. Will it have access to outer variables from its creation place or the invocation place or maybe both? ```js function makeWorker() { let name = "Pete"; return function() { alert(name); }; } let name = "John"; // create a function let work = makeWorker(); // call it *!* work(); // what will it show? "Pete" (name where created) or "John" (name where called)? */!* ``` ## Lexical Environment To understand what's going on, let's first discuss what a "variable" technically is. In JavaScript, every running function, code block and the script as a whole have an associated object named *Lexical Environment*. The Lexical Environment object consists of two parts: 1. *Environment Record* -- an object that has all local variables as its properties (and some other information like the value of `this`). 2. An reference to the *outer lexical environment*, usually the one associated with the code lexically right outside of it (outside of the current figure brackets). So, a "variable" is just a property of the special internal object, Environment Record. "To get or change a variable" means "to get or change the property of that object". For instance, in this simple code, there is only one Lexical Environment: ![lexical environment](lexical-environment-global.png) This is a so-called global Lexical Environment, associated with the whole script. For browsers, all `