- 10. Variables and assignment
- 10.1. let
- 10.2. const
- 10.3. Deciding between let and const
- 10.4. The scope of a variable
- 10.5. (Advanced)
- 10.6. Terminology: static vs. dynamic
- 10.7. Temporal dead zone: preventing access to a variable before its declaration
- 10.8. Hoisting
- 10.9. Global variables
- 10.10. Closures
- 10.11. Summary: ways of declaring variables
- 10.12. Further reading
10. Variables and assignment
These are JavaScript’s main ways of declaring variables:
let
declares mutable variables.const
declares constants (immutable variables).
Before ES6, there was alsovar
. But it has several quirks, so it’s best to avoid it in modern JavaScript. You can read more about it in “Speaking JavaScript”.
10.1. let
Variables declared via let
are mutable:
You can also declare and assign at the same time:
10.2. const
Variables declared via const
are immutable. You must always initialize immediately:
10.2.1. const and immutability
In JavaScript, const
only means that the binding (the association between variable name and variable value) is immutable. The value itself may be mutable, like obj
in the following example.
10.2.2. const and loops
You can use const
with for-of
loops, where a fresh binding is created for each iteration:
In plain for
loops, you must use let
, however:
10.3. Deciding between let and const
I recommend the following rules to decide between let
and const
:
const
indicates an immutable binding and that a variable never changes its value. Prefer it.let
indicates that the value of a variable changes. Use it only when you can’t useconst
.
10.4. The scope of a variable
The scope of a variable is the region of a program where it can be accessed. Consider the following code.
{ // // Scope A. Accessible: x
const x = 0;
assert.equal(x, 0);
{ // Scope B. Accessible: x, y
const y = 1;
assert.equal(x, 0);
assert.equal(y, 1);
{ // Scope C. Accessible: x, y, z
const z = 2;
assert.equal(x, 0);
assert.equal(y, 1);
assert.equal(z, 2);
}
}
}
// Outside. Not accessible: x, y, z
assert.throws(
() => console.log(x),
{
name: 'ReferenceError',
message: 'x is not defined',
}
);
- Scope A is the (direct) scope of
x
. - Scopes B and C are inner scopes of scope A.
- Scope A is an outer scope of scope B and scope C.
Each variable is accessible in its direct scope and all scopes nested within that scope.
The variables declared via const
and let
are called block-scoped, because their scopes are always the innermost surrounding blocks.
10.4.1. Shadowing and blocks
You can’t declare the same variable twice at the same level:
You can, however, nest a block and use the same variable name x
that you used outside the block:
Inside the block, the inner x
is the only accessible variable with that name. The inner x
is said to shadow the outer x
. Once you leave the block, you can access the old value again.
10.5. (Advanced)
All remaining sections are advanced.
10.6. Terminology: static vs. dynamic
These two adjectives describe phenomena in programming languages:
- Static means that something is related to source code and can be determined without executing code.
- Dynamic means at runtime.
Let’s look at examples for these two terms.
10.6.1. Static phenomenon: scopes of variables
Variable scopes are a static phenomenon. Consider the following code:
x
is statically (or lexically) scoped. That is, its scope is fixed and doesn’t change at runtime.
Variable scopes form a static tree (via static nesting).
10.6.2. Dynamic phenomenon: function calls
Function calls are a dynamic phenomenon. Consider the following code:
Whether or not the function call in line A happens, can only be decided at runtime.
Function calls form a dynamic tree (via dynamic calls).
10.7. Temporal dead zone: preventing access to a variable before its declaration
For JavaScript, TC39 needed to decide what happens if you access a variable in its direct scope, before its declaration:
Some possible approaches are:
- The name is resolved in the scope surrounding the current scope.
- If you read, you get
undefined
. You can also already write to the variable. (That’s howvar
works.) - There is an error.
TC39 chose (3) forconst
andlet
, because you likely made a mistake, if you use a variable name that is declared later in the same scope. (2) would not work forconst
(where each variable should always only have the value that it is initialized with). It was therefore also rejected forlet
, so that both work similarly and it’s easy to switch between them.
The time between entering the scope of a variable and executing its declaration is called the temporal dead zone (TDZ) of that variable:
- During this time, the variable is considered to be uninitialized (as if that were a special value it has).
- If you access an unitialized variable, you get a
ReferenceError
. - Once you reach a variable declaration, the variable is set to either the value of the initializer (specified via the assignment symbol) or
undefined
– if there is no initializer.
The following code illustrates the temporal dead zone:
The next example shows that the temporal dead zone is truly temporal (related to time):
Even though func()
is located before the declaration of myVar
and uses that variable, we can call func()
. But we have to wait until the temporal dead zone of myVar
is over.
10.8. Hoisting
Hoisting means that a construct is moved to the beginning of its scope, regardless of where it is located in that scope:
You can use func()
before its declaration, because, internally, it is hoisted. That is, the previous code is actually executed like this:
The temporal dead zone can be viewed as a form of hoisting, because the declaration affects what happens at the beginning of its scope.
10.9. Global variables
A variable is global if it is declared in the top-level scope. Every nested scope can access such a variable. In JavaScript, there are multiple layers of global scopes (Fig. 5):
The outermost global scope is special: its variables can be accessed via the properties of an object, the so-called global object. The global object is referred to by
window
andself
in browsers. Variables in this scope are created via:- Properties of the global object
var
andfunction
at the top level of a script. (Scripts are supported by browsers. They are simple pieces of code and precursors to modules. Consult the chapter on modules for details.)
Nested in that scope is the global scope of scripts. Variables in this scope are created by
let
,const
andclass
at the top level of a script.Nested in that scope are the scopes of modules. Each module has its own global scope. Variables in that scope are created by declarations at the top level of the module.
10.9.1. The global object
The global object lets you access the outermost global scope via an object. The two are always in sync:
- If you create a variable in the outermost global scope, the global object gets a new property. If you change such a global variable, the property changes.
If you create or delete a property of the global object, the corresponding global variable is created or deleted. If you change a property of the global object, the corresponding global variable changes.
The global object is available via special variables:window
: is the classic way of referring to the global object. But it only works in normal browser code, not in Node.js and not in Web Workers (processes running concurrently to normal browser code; consult the chapter on asynchronous programming for details).self
: is available everywhere in browsers, including in Web Workers. But it isn’t supported by Node.js.global
: is only available in Node.js.
Let’s examine howself
works:
// At the top level of a script
var myGlobalVariable = 123;
assert.equal('myGlobalVariable' in self, true);
delete self.myGlobalVariable;
assert.throws(() => console.log(myGlobalVariable), ReferenceError);
// Create a global variable anywhere:
if (true) {
self.anotherGlobalVariable = 'abc';
}
assert.equal(anotherGlobalVariable, 'abc');
10.9.2. Avoid the global object!
Brendan Eich called the global object one of his biggest regrets about JavaScript. It is best not to put variables into its scope:
- In general, variables that are global to all scripts on a web page, risk name clashes.
- Via the global object, you can create and delete global variables anywhere. Doing so makes code unpredictable, because it’s normally not possible to make this kind of change in nested scopes.
You occasionally seewindow.globalVariable
in tutorials on the web, but the prefix “window.
” is not necessary. I prefer to omit it:
10.10. Closures
Before we can explore closures, we need to learn about bound variables and free variables.
10.10.1. Bound variables vs. free variables
Per scope, there is a set of variables that are mentioned. Among these variables we distinguish:
- Bound variables are declared within the scope. They are parameters and local variables.
- Free variables are declared externally. They are also called non-local variables.
Consider the following code:
In the body of func()
, x
and y
are bound variables. z
is a free variable.
10.10.2. What is a closure?
What is a closure, then?
A closure is a function plus a connection to the variables that exist at its “birth place”.
What is the point of keeping this connection? It provides the values for the free variables of the function. For example:
funcFactory
returns a closure that is assigned to func
. Because func
has the connection to the variables at its birth place, it can still access the free variable value
when it is called in line A (even though it “escaped” its scope).
10.10.3. Example: A factory for incrementors
The following function returns incrementors (a name that I just made up). An incrementor is a function that internally stores a number. When it is called, it updates that number by adding the argument to it and returns the new value.
We can see that the function created in line A keeps its internal number in the free variable startValue
. This time, we don’t just read from the birth scope, we use it to store data that we change and that persists across function calls.
We can create more storage slots in the birth scope, via local variables:
10.10.4. Use cases for closures
What are closures good for?
For starters, they are simply an implementation of static scoping. As such, they provide context data for callbacks.
They can also be used by functions to store state that persists across function calls.
createInc()
is an example of that.And they can provide private data for object (produced via literals or classes). The details of how that works are explained in “Exploring ES6”.
10.11. Summary: ways of declaring variables
Hoisting | Scope | Script scope is global object? | |
---|---|---|---|
var | Declaration only | Function | ✔ |
let | Temporal dead zone | Block | ✘ |
const | Temporal dead zone | Block | ✘ |
function | Everything | Block | ✔ |
class | No | Block | ✘ |
import | Everything | Module | ✘ |
Tbl. 1 lists all ways in which you can declare variables in JavaScript: var
, let
, const
, function
, class
and import
.
10.12. Further reading
For more information on how variables are handled under the hood, consult the chapter “Variable environments”.