Book Image

Object-Oriented JavaScript

Book Image

Object-Oriented JavaScript

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
Built-in Functions
Regular Expressions
Index

Variables


Variables are used to store data. When writing programs, it is convenient to use variables instead of the actual data, as it's much easier to write pi instead of 3.141592653589793 especially when it happens several times inside your program. The data stored in a variable can be changed after it was initially assigned, hence the name "variable". Variables are also useful for storing data that is unknown to the programmer when the code is written, such as the result of later operations.

There are two steps required in order to use a variable. You need to:

  • Declare the variable

  • Initialize it, that is, give it a value

In order to declare a variable, you use the var statement, like this:

var a; 
var thisIsAVariable; 
var _and_this_too; 
var mix12three;

For the names of the variables, you can use any combination of letters, numbers, and the underscore character. However, you can't start with a number, which means that this is invalid:

var 2three4five;

To initialize a variable means to give...