Variables - JavaScript - The Definitive Guide, 5th Edition (Book)
Variables - JavaScript - The Definitive Guide, 5th Edition (Book)
i = 2;
And the following line adds 3 to i and assigns the result to a new variable,
sum:
var sum = i + 3;
These two lines of code demonstrate just about everything you need to
know about variables. However, to fully understand how variables work in
JavaScript, you need to master a few more concepts. Unfortunately, these
concepts require more than a couple of lines of code to explain! The rest of
this chapter explains the typing, declaration, scope, contents, and resolution
SIGN IN TRY NOW
of variables. It also explores garbage collection and the variable/property
duality.[*]
Variable Typing
An important difference between JavaScript and languages such as Java and
C is that JavaScript is untyped. This means, in part, that a JavaScript variable
can hold a value of any datatype, unlike a Java or C variable, which can hold
only the one particular type of data for which it is declared. For example, it is
perfectly legal in JavaScript to assign a number to a variable and then later
assign a string to that variable:
i = 10;
i = "ten";
In C, C++, Java, or any other strongly typed language, code like this is illegal.
Before you use a variable in a JavaScript program, you must declare it.[*]
Variables are declared with the var keyword, like this:
var i;
var sum;
You can also declare multiple variables with the same var keyword:
var i, sum;
If you donât specify an initial value for a variable with the var statement,
the variable is declared, but its initial value is undefined until your code
stores a value into it.
Note that the var statement can also appear as part of the for and for/in
loops (introduced in Chapter 6), allowing you to succinctly declare the loop
variable as part of the loop syntax itself. For example:
Variables declared with var are permanent: attempting to delete them with
the delete operator causes an error. (The delete operator is introduced in
Chapter 5.)
SIGN IN TRY NOW
It is legal and harmless to declare a variable more than once with the var
statement. If the repeated declaration has an initializer, it acts as if it were
simply an assignment statement.
Variable Scope
The scope of a variable is the region of your program in which it is defined. A
global variable has global scope; it is defined everywhere in your JavaScript
code. On the other hand, variables declared within a function are defined
only within the body of the function. They are local variables and have local
scope. Function parameters also count as local variables and are defined
only within the body of the function.
Although you can get away with not using the var statement when you
write code in the global scope, you must always use var to declare local
variables. Consider what happens if you donât:
In general, functions do not know what variables are defined in the global
scope or what they are being used for. Thus, if a function uses a global vari-
able instead of a local one, it runs the risk of changing a value on which
some other part of the program relies. Fortunately, avoiding this problem is
simple: declare all variables with var.
Function definitions can be nested. Each function has its own local scope, so
it is possible to have several nested layers of local scope. For example:
var scope = "global scope"; // A global variable
SIGN IN TRY NOW
function checkscope( ) {
var scope = "local scope"; // A local variable
function nested( ) {
var scope = "nested scope"; // A nested scope of local varia
document.write(scope); // Prints "nested scope"
}
nested( );
}
checkscope( );
No Block Scope
Note that unlike C, C++, and Java, JavaScript does not have block-level
scope. All variables declared in a function, no matter where they are de-
clared, are defined throughout the function. In the following code, the vari-
ables i, j, and k all have the same scope: all three are defined throughout
the body of the function. This would not be the case if the code were written
in C, C++, or Java:
function test(o) {
var i = 0; // i is defined throughout functi
if (typeof o == "object") {
var j = 0; // j is defined everywhere, not j
for(var k=0; k < 10; k++) { // k is defined everywhere, not j
document.write(k);
}
document.write(k); // k is still defined: prints 10
}
document.write(j); // j is defined, but may not be i
}
The rule that all variables declared in a function are defined throughout the
function can cause surprising results. The following code illustrates this:
var scope = "global";
SIGN IN TRY NOW
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined e
alert(scope); // Displays "local"
}
f( );
You might think that the first call to alert( ) would display âglobalâ,
because the var statement declaring the local variable has not yet been ex-
ecuted. Because of the scope rules, however, this is not what happens. The
local variable is defined throughout the body of the function, which means
the global variable by the same name is hidden throughout the function.
Although the local variable is defined throughout, it is not actually initialized
until the var statement is executed. Thus, the function f in the previous ex-
ample is equivalent to the following:
function f( ) {
var scope; // Local variable is declared at the start of th
alert(scope); // It exists here, but still has "undefined" val
scope = "local"; // Now we initialize it and give it a value
alert(scope); // And here it has a value
}
The second kind of undefined variable is one that has been declared but has
never had a value assigned to it. If you read the value of one of these vari-
ables, you obtain its default value, undefined. This type of undefined vari-
able might more usefully be called unassigned, to distinguish it from the
more serious kind of undefined variable that has not even been declared and
does not exist.
A primitive type has a fixed size in memory. For example, a number occupies
eight bytes of memory, and a boolean value can be represented with only
one bit. The number type is the largest of the primitive types. If each
JavaScript variable reserves eight bytes of memory, the variable can directly
SIGN IN TRY NOW
hold any primitive value.[*]
Reference types are another matter, however. Objects, for example, can be
of any length: they do not have a fixed size. The same is true of arrays: an ar-
ray can have any number of elements. Similarly, a function can contain any
amount of JavaScript code. Since these types do not have a fixed size, their
values cannot be stored directly in the eight bytes of memory associated
with each variable. Instead, the variable stores a reference to the value.
Typically, this reference is some form of pointer or memory address. It is not
the data value itself, but it tells the variable where to look to find the value.
There is nothing surprising about this code. Now consider what happens if
we change the code slightly so that it uses arrays (a reference type) instead
of numbers:
If this result does not seem surprising to you, youâre already well familiar
with the distinction between primitive and reference types. If it does seem
surprising, take a closer look at the second line. Note that it is the reference
to the array value, not the array itself, that is being assigned in this state-
SIGN IN TRY NOW
ment. After that second line of code, we still have only one array object;
there just happens to be two references to it.
You may have noticed that I did not specify whether strings are primitive or
reference types in JavaScript. Strings are an unusual case. They have variable
sizes, so obviously they cannot be stored directly in fixed-size variables. For
efficiency, you would expect JavaScript to copy references to strings, not
the actual contents of strings. On the other hand, strings behave like a prim-
itive type in many ways. The question of whether strings are a primitive or
reference type is actually moot because strings are immutable: there is no
way to change the contents of a string value. This means that you cannot
construct an example like the previous one that demonstrates that arrays are
copied by reference. In the end, it doesnât matter much whether you think
of strings as an immutable reference type that behaves like a primitive type
or as a primitive type implemented with the internal efficiency of a reference
type.
Garbage Collection
Reference types do not have a fixed size; indeed, some of them can become
quite large. As weâve already discussed, variables do not directly hold ref-
erence values. The value is stored at some other location, and the variables
merely hold a reference to that location. Now letâs focus briefly on the ac-
tual storage of the value.
Since strings, objects, and arrays do not have a fixed size, storage for them
SIGN IN TRY NOW
must be allocated dynamically, when the size is known. Every time a
JavaScript program creates a string, array, or object, the interpreter must al-
locate memory to store that entity. Whenever memory is dynamically allo-
cated like this, it must eventually be freed up for reuse, or the JavaScript in-
terpreter will use up all the available memory on the system and crash.
After this code runs, the original string âhelloâ is no longer reachable;
there are no references to it in any variables in the program. The system de-
tects this fact and frees up its storage space for reuse.
You may have noticed by now that there are a lot of similarities in JavaScript
between variables and the properties of objects. They are both assigned the
same way, they are used the same way in JavaScript expressions, and so on.
Is there really any fundamental difference between the variable i and the
property i of an object o? The answer is no. Variables in JavaScript are fun-
damentally the same as object properties.
When the JavaScript interpreter starts up, one of the first things it does, be-
fore executing any JavaScript code, is create a global object. The properties
of this object are the global variables of JavaScript programs. When you de-
clare a global JavaScript variable, what you are actually doing is defining a
property of the global object.
In top-level code (i.e., JavaScript code that is not part of a function), you can
use the JavaScript keyword this to refer to the global object. Within func-
tions, this has a different use, which is described in Chapter 8.
In client-side JavaScript, the Window object serves as the global object for
all JavaScript code contained in the browser window it represents. This
global Window object has a self-referential window property that can be
used instead of this to refer to the global object. The Window object de-
fines the core global properties, such as parseInt and Math, and also
global client-side properties, such as navigator and screen.
Local Variables: The Call Object
SIGN IN TRY NOW
If global variables are properties of the special global object, then what are
local variables? They too are properties of an object. This object is known as
the call object. The call object has a shorter lifespan than the global object,
but it serves the same purpose. While the body of a function is executing,
the function arguments and local variables are stored as properties of this
call object. The use of an entirely separate object for local variables is what
allows JavaScript to keep local variables from overwriting the value of
global variables with the same name.
Every JavaScript execution context has a scope chain associated with it. This
scope chain is a list or chain of objects. When JavaScript code needs to look
up the value of a variable x (a process called variable name resolution), it
starts by looking at the first object in the chain. If that object has a property
named x, the value of that property is used. If the first object does not have
a property named x, JavaScript continues the search with the next object in
the chain. If the second object does not have a property named x, the search
moves on to the next object, and so on.
In top-level JavaScript code (i.e., code not contained within any function
definitions), the scope chain consists of a single object, the global object. All
variables are looked up in this object. If a variable does not exist, the vari-
able value is undefined. In a (nonnested) function, however, the scope chain
consists of two objects. The first is the functionâs call object, and the sec-
ond is the global object. When the function refers to a variable, the call ob-
ject (the local scope) is checked first, and the global object (the global
scope) is checked second. A nested function would have three or more ob-
jects in its scope chain. Figure 4-1 illustrates the process of looking up a
variable name in the scope chain of a function.
SIGN IN TRY NOW
[*] Theseare tricky concepts, and a complete understanding of this chapter requires an understanding of concepts introduced in later chapters of the book. If you are
relatively new to programming, you may want to read only the first two sections of this chapter and then move on to Chapter 5, 6, and 7 before returning to finish
up the remainder of this chapter.
[*] If you donât declare a variable explicitly, JavaScript will declare it implicitly for you.
[*] This is an oversimplification and is not intended as a description of an actual JavaScript implementation.
[*] This is merely an aside; if it does not interest you, feel free to move on to the next section.
Get JavaScript: The Definitive Guide, 5th Edition now with the
O’Reilly learning platform.
ABOUT O’REILLY
Teach/write/train
Careers
Press releases
Media coverage
Community partners
Affiliate program
Submit an RFP
Diversity
SUPPORT
Contact us
Newsletters
Privacy policy
INTERNATIONAL
India
Indonesia
Japan
Take O’Reilly with you and learn anywhere, anytime on your phone and tablet.
WATCH ON YOUR BIG SCREEN
View all O’Reilly videos, Superstream events, and Meet the Expert sessions SIGN INhomeTRY
on your TV.NOW
© 2023, O’Reilly Media, Inc. All trademarks and registered trademarks appearing on oreilly.com are the property of their
respective owners.
Terms of service • Privacy policy • Editorial independence