# Closure JavaScript is a very function-oriented language. It gives us 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; this feature is used quite often. But what happens when an outer variable changes? Does a function get the most recent value or the one that existed when the function was created? Also, what happens when a function travels to another place in the code and is called from there -- does it get access to the outer variables of the new place? Different languages behave differently here, and in this chapter we cover the behaviour of JavaScript. ## A couple of questions Let's consider two situations to begin with, and then study the internal mechanics piece-by-piece, so that you'll be able to answer the following questions and more complex ones in the future. 1. The function `sayHi` uses an external variable `name`. When the function runs, which value is it 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 both in 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 the 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 the outer variables from its creation place, or the invocation place, or 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" actually is. In JavaScript, every running function, code block, and the script as a whole have an associated object known as the *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 curly 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 a property of the Lexical Environment". 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 `