# Closure JavaScript is a very function-oriented language. It gives a lot of freedom. A function can be created at one moment, then copied to another variable or passed as an argument to another function and called from a totally different place later. We know that a function can access variables outside of it. And this feature is used quite often. But what happens when an outer variables changes? Does a function get a most recent value or the one that existed when the function was created? Also, what happens when a function travels to another place of the code and is called from there -- does it get access to outer variables in the new place? Different languages behave differently here, in this chapter we cover JavaScript. [cut] ## A couple of questions Let's formulate two questions for the seed, and then study the internal mechanics piece-by-piece, so that you'll be able to answer these questions and more complex ones in the future. 1. The function `sayHi` uses an external variable `name`. When the function runs, which value of these two it's going to use? ```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, for instance after a user action or a network request. So, 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. A reference to the *outer lexical environment*, usually the one associated with the code lexically right outside of it (outside of the current figure brackets).a 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 `