JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

10. Variables and assignment



These are JavaScript’s main ways of declaring variables:

Before ES6, there was also var. 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:

let i;
i = 0;
i = i + 1;
assert.equal(i, 1);

You can also declare and assign at the same time:

let i = 0;

10.2. const

Variables declared via const are immutable. You must always initialize immediately:

const i = 0; // must initialize

assert.throws(
  () => { i = i + 1 },
  {
    name: 'TypeError',
    message: 'Assignment to constant variable.',
  }
);

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.

const obj = { prop: 0 };

// Allowed: changing properties of `obj`
obj.prop = obj.prop + 1;
assert.equal(obj.prop, 1);

// Not allowed: assigning to `obj`
assert.throws(
  () => { obj = {} },
  {
    name: 'TypeError',
    message: 'Assignment to constant variable.',
  }
);

10.2.2. const and loops

You can use const with for-of loops, where a fresh binding is created for each iteration:

const arr = ['hello', 'world'];
for (const elem of arr) {
  console.log(elem);
}
// Output:
// 'hello'
// 'world'

In plain for loops, you must use let, however:

const arr = ['hello', 'world'];
for (let i=0; i<arr.length; i++) {
  const elem = arr[i];
  console.log(elem);
}

10.3. Deciding between let and const

I recommend the following rules to decide between let and const:

  Exercise: const

exercises/variables-assignment/const_exrc.js

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',
  }
);

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:

assert.throws(
  () => {
    eval('let x = 1; let x = 2;');
  },
  {
    name: 'SyntaxError',
    message: "Identifier 'x' has already been declared",
  });

  Why eval()?

We need to delay parsing via eval(), otherwise we already get an exception when this code is parsed. assert.throws() only works if an exception is thrown inside the body of its function.

You can, however, nest a block and use the same variable name x that you used outside the block:

const x = 1;
assert.equal(x, 1);
{
  const x = 2;
  assert.equal(x, 2);
}
assert.equal(x, 1);

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.

  Quiz: basic

See quiz app.

10.5. (Advanced)

All remaining sections are advanced.

10.6. Terminology: static vs. dynamic

These two adjectives describe phenomena in programming languages:

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:

function f() {
  const x = 3;
  // ···
}

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:

function g(x) {}
function h(y) {
  if (Math.random()) g(y); // (A)
}

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:

{
  console.log(x); // What happens here?
  let x;
}

Some possible approaches are:

  1. The name is resolved in the scope surrounding the current scope.
  2. If you read, you get undefined. You can also already write to the variable. (That’s how var works.)
  3. There is an error.

TC39 chose (3) for const and let, because you likely made a mistake, if you use a variable name that is declared later in the same scope. (2) would not work for const (where each variable should always only have the value that it is initialized with). It was therefore also rejected for let, 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:

The following code illustrates the temporal dead zone:

if (true) { // entering scope of `tmp`, TDZ starts
  // `tmp` is uninitialized:
  assert.throws(() => (tmp = 'abc'), ReferenceError);
  assert.throws(() => console.log(tmp), ReferenceError);

  let tmp; // TDZ ends
  assert.equal(tmp, undefined);
}

The next example shows that the temporal dead zone is truly temporal (related to time):

if (true) { // entering scope of `myVar`, TDZ starts
  const func = () => {
    console.log(myVar); // executed later
  };

  // We are within the TDZ:
  // Accessing `myVar` causes `ReferenceError`

  let myVar = 3; // TDZ ends
  func(); // OK, called outside TDZ
}

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:

assert.equal(func(), 123); // Works!

function func() {
  return 123;
}

You can use func() before its declaration, because, internally, it is hoisted. That is, the previous code is actually executed like this:

function func() {
  return 123;
}

assert.equal(func(), 123);

The temporal dead zone can be viewed as a form of hoisting, because the declaration affects what happens at the beginning of its scope.

  More on hoisting functions

For more information on how hoisting affects functions, consult the chapter on callable values.

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):

Figure 5: JavaScript has multiple global scopes.
Figure 5: JavaScript has multiple global scopes.

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:

The global object is available via special variables:

Let’s examine how self 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:

You occasionally see window.globalVariable in tutorials on the web, but the prefix “window.” is not necessary. I prefer to omit it:

window.encodeURIComponent(str); // no
encodeURIComponent(str); // yes

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:

Consider the following code:

function func(x) {
  const y = 123;
  console.log(z);
}

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:

function funcFactory(value) {
  return () => {
    return value;
  };
}

const func = funcFactory('abc');
assert.equal(func(), 'abc'); // (A)

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).

  All functions in JavaScript are closures

Static scoping is supported via closures in JavaScript. Therefore, every function is a closure. Consult the chapter “Variable environments”) if you are interested in how closures work under the hood (as described in the ECMAScript specification).

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.

function createInc(startValue) {
  return (step) => { // (A)
    startValue += step;
    return startValue;
  };
}
const inc = createInc(5);
assert.equal(inc(2), 7);

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:

function createInc(startValue) {
  let index = -1;
  return (step) => {
    startValue += step;
    index++;
    return [index, startValue];
  };
}
const inc = createInc(5);
assert.deepEqual(inc(2), [0, 7]);
assert.deepEqual(inc(2), [1, 9]);
assert.deepEqual(inc(2), [2, 11]);

10.10.4. Use cases for closures

What are closures good for?

10.11. Summary: ways of declaring variables

Table 1: These are all the ways in which you declare variables in JavaScript.
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.

  Quiz: advanced

See quiz app.

10.12. Further reading

For more information on how variables are handled under the hood, consult the chapter “Variable environments”.