Skip to Content
JavaScript: The Definitive Guide, 5th Edition
book

JavaScript: The Definitive Guide, 5th Edition

by David Flanagan
August 2006
Intermediate to advanced
1018 pages
34h 13m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, 5th Edition

Chapter 4. Variables

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.[*]

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.

A feature related to JavaScript’s lack of typing is that the language conveniently and automatically converts values from ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: The Definitive Guide, 7th Edition

JavaScript: The Definitive Guide, 7th Edition

David Flanagan
JavaScript from Beginner to Professional

JavaScript from Beginner to Professional

Rob Percival, Laurence Svekis, Maaike van Putten, Codestars By Rob Percival

Publisher Resources

ISBN: 0596101996Supplemental ContentErrata Page