Variables

How does a program keep an internal state? How does it remember things? We have seen how to produce new values from old values, but this does not change the old values, and the new value has to be immediately used or it will dissipate again. To catch and hold values, JavaScript provides a thing called a variable.

var caught = 5 * 5;

A variable always has a name, and it can point at a value, holding on to it. The previous statement creates a variable called caught and uses it to grab hold of the number that is produced by multiplying 5 by 5.

After a variable has been defined, its name can be used as an expression that produces the value it holds. Here’s an example:

var ten = 10;
ten * ten;
→ 100

The word var is used to create a new variable. ...

Get Eloquent JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.