JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

Chapter 4. Variables

Contents:

Variable Typing
Variable Declaration
Variable Scope
Primitive Types and Reference Types
Garbage Collection
Variables as Properties
Variable Scope Revisited

A variable is a name associated with a value; we say that the variable stores or contains the value. Variables allow you to store and manipulate data in your programs. For example, the following line of JavaScript assigns the value 2 to a variable named i:

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 of variables. It also explores garbage collection and the variable/property duality.[11]

[11]These are 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, Chapter 6, and Chapter 7 before returning to finish up the remainder of this chapter.

4.1. 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 data type, 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.

A feature related to JavaScript's lack of typing is that the language conveniently and automatically converts values from one type to another, as necessary. If you attempt to append a number to a string, for example, JavaScript automatically converts the number to the corresponding string so that it can be appended. We'll see more about data type conversion in Chapter 11.

JavaScript is obviously a simpler language for being untyped. The advantage of strongly typed languages such as C++ and Java is that they enforce rigorous programming practices, which makes it easier to write, maintain, and reuse long, complex programs. Since many JavaScript programs are shorter scripts, this rigor is not necessary and we benefit from the simpler syntax.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.