Print this Section


Data Types and Variables

Computer programs are processors of data. They take numbers, letters, and other special characters and manipulate them in some fashion for the purpose of producing information. They attempt, in other words, to assign meaning to bits and pieces of data by applying actions such as calculating, categorizing, arranging, presenting, or otherwise manipulating and organizing the data to derive useful information. In JavaScript, data are recognized as one of three types: numeric, string, and Boolean.

Numeric Data Type

Numeric data are composed of the numerals 0 - 9 plus the decimal point. JavaScript recognizes two kinds of numbers: integer positive or negative whole numbers composed only of the decimal digits 0 - 9; floating-point numbers are composed of the decimal digits plus a decimal point. Thus, the value 12345 is an integer number and the value 123.45 is a floating-point number. JavaScript recognizes numbers when they appear in decimal notation (as above), in scientific notation (123.45E6), in hexadecimal (0XFF00CC), or in octal (012345). Numeric data are defined for the purpose of applying mathematical operations to them.

String Data Type

String data are composed of the lower-case alphabetic characters a - z, the upper-case characters A - Z, the numerals 0 - 9, plus special characters such as $, #, &, _, and others. Strings are identified by enclosing them in quotes: "This is a string of characters." Character strings are treated as single blocks of text that can be put together (concatenated) to create a longer character string from the separate strings, or they can be taken apart to extract substrings composed of portions of the string.

Since quotes are used to surround and define text strings, a special situation arises when you want to include quotation marks as part of a text string. You cannot just include them in the middle of the string as follows:

"Here is a string with a "quote" marks inside."

This notation violates the definitional rules of a string and confuses JavaScript. Since pairs of quote marks surround and define a string, this line is interpreted as three separate elements: the string "Here is a string with a " is followed by the word quote, which is followed by a second string " marks inside." This is clearly not what is intended.

There are a couple of ways to handle this situation. You can mark embedded quotes with a preceding backslash character (\), technically called escaping the quote character:

"Here is a string with \"quote\" marks."

This format indicates that the embedded quotation mark does not enclose a string; it is a character within a string. You can also enclose the entire string inside single quotes (apostrophes) to differentiate between the two quote types:

'Here is a string with "quote" marks.'

This latter technique of alternating quote characters is probably the easiest way to distinguish between embedded quotes and enclosing quotes, although it does beg the question of what to do about quoted strings that contain both embedded quotes and embedded apostrophes:

'Here's a string with "quote" marks.'

This construction is invalid because JavaScript interprets the apostrophe as ending the string begun with the initial single quote. So, you need to put together alternating quotes and escaped characters that make sense to JavaScript:

"Here's a string with \"quote\" marks." or 'Here\'s a string with "quote" marks.'

The point is, you need to be careful when composing text strings that themselves enclose quote marks and apostrophes to make sure that the entire string is treated as a single entity.

In addition to the \" double quotation mark used above, JavaScript also includes the following useful escape sequences:

Escape SequenceCharacter
\rCarriage Return
\tHorizontal Tab
\nNew line
\'Single Quote

Boolean Data Type

Boolean data consists of two values: true and false. This data type is used in script decision making, a topic covered later where you will see the application of this data type.

Null Value Data Type

An empty value. Assigning a null value to a variable indicates that the variable contains no usable value.

Undefined Data

A variable that has never had a value assigned to it, has not been declared, or does not exist.

Javascript also supports composite, or reference data types. These data types can contain multiple values as opposed to a single or scalar value. Three composite types supported by Javascript include arrays, functions, and objects. These data types will be discussed in more detail later.

typeof Operator

JavaScript includes the typeof operator that can be used to determine the data type of a variable. This is useful because the data type of JavaScript variables can change during the course of program execution. The syntax of the operator is shown below:


The typeof operator can return the following values:

Return ValueReturned For
BooleanTrue or False
NumberIntegers and Floating-point numbers
ObjectArrays and null variables
StringText Strings
UndefinedUndefined variables

JavaScript Variables

A computer program that processes data must set aside storage areas in computer memory where numeric, string, and Boolean data can be placed, and from which they can be accessed in order to process them. Programs create these storage areas by defining program variables.

A variable is a named memory location. Once defined, it is available as a place to store data temporarily while a program, or script, is running. The script can assign data to that location, retrieve data from the location for processing, and put processing results back into that location.

In JavaScript, a variable is created by naming it. There are, however, naming conventions that must be followed. Variable names

  • must begin with an alphabetic character or the underscore ( _ ) character
  • can be composed of letters, numerals, or the underscore character
  • cannot contain blank spaces
  • cannot be the same as a JavaScript reserved word, which is a word that has a special meaning in the JavaScript language.

Otherwise, you are free to name your variables as you wish. It makes sense, of course, to assign names that are meaningful and that help identify the kinds of data being stored in the associated memory locations.

Variable names are case sensitive. That is, JavaScript differentiates between upper-case and lower-case characters. Therefore, variable myName references a different memory location from my_name or MY_NAME. Make sure you pay careful attention to the case of the variable names you assign and use them consistently.

Declaring Variables

The formal method of establishing and naming variables is to declare them in a JavaScript statement with the keyword var. This word is followed by the name you wish to assign to the variable as shown in the general format in Figure 2-1.

var myVariable;

Figure 2-1. General format to declare a JavaScript variable.

This format is illustrated in the following examples of declaring variables inside a script.

var lastName;
var soc_Sec_No;
var current_date;

Here, three different storage locations are named and set aside to contain data; plus, the variable names suggest the kinds of data to be placed in these locations. Any time a script needs to refer to or access the stored data, it does so through the names assigned to these locations. This is an important point. A script reference to a variable name is a reference to the actual data value residing in the named memory location.

Notice also in the above example that a semicolon is used to terminate each declaration statement. Doing so permits more than one statement to be placed on a single line of code by explicitly terminating each statement. If, however, only a single statement appears on a line, use of the semicolon is optional. The convention followed in these tutorials is to always terminate a statement with a semicolon, which is in keeping with common JavaScript practice.

Assigning Data to Variables

Data are placed into variables by using the JavaScript assignment statement. General formats for the assignment statement include those shown in Figure 2-2.

variable = number;
variable = "string"
variable = true|false

Figure 2-2. General formats to assign data to variables.

The data value appearing on the right of the equal sign is assigned to (placed in) the variable named on the left of the equal sign. This value can be an integer or floating-point number, it can be a text string enclosed in quotes, or it can be one of the Boolean values true or false. For example, if you have declared the following variables,

var myNumber;
var myString;
var myTest;

then you can place data into the these variables with the assignments:

myNumber = 12345;
myString = "A text string";
myTest = true;

As you can see, the keyword var is used only the first time a variable is declared. Subsequently, the variable name by itself references the existing variable.

You can see the results of these statements below. Click on the radio buttons in sequence to execute the statements and watch the declarations and assignments of values to the three variables.

Computer Memory:


Figure 2-3. Declaring and assigning values to variables.

Incidentally, you can combine the two actions of declaring a variable and assigning data to it within a single statement:

var myNumber = 12345;
var myString = "A text String ";
var myTest = true;

This combined declaration and assignment is appropriate to establish the initial value for a variable when the value is known in advance. In many cases, however, you will not know the value that variable will take on; it will depend on the JavaScript processing that produces the value. In this case, you need only to declare the variable without assigning its value.

Technically, you do not have to use the var keyword. You can declare a variable and assign a value with, simply,

myNumber = 12345
myString = "A Text String";
myTest = true;

Still, it is conventional to follow the formal method of declaring a variable with the keyword var. You will also notice in the examples that blank spaces appear before and after the equal sign in the assignment statements. You can use spaces freely in JavaScript to make your code more readable.

In each of the examples above, the process of assigning data to a variable does not require you declare the data type of the variable. Instead, Javascript determines the data type of the variable based on the value assigned to the variable. Unlike most programming languages, Javascript is known as a loosely typed programming language. In fact, in Javascript you are not allowed to declare the data type of a variable. The data type is always determined by the type of data assigned to the variable. For this reason, the data type of variable can change depending on the data assigned to the variable. This is in contrast to other languages such as Java, Visual Basic, and C++ that are strongly typed languages where you are required to explicitly declare the data type of a variable.

Assigning Variables to Variables

In the above examples, literal data values are assigned to variables—an actual number, text string, or Boolean value is placed in the variable. You also can assign the contents of one variable to another variable with the syntax shown in Figure 2-4.

variable1 = variable2;

Figure 2-4. General format to assign a variable value to a different variable.

Consider the following five lines of code:

var firstString;
var secondString;

firstString = "Hello World";
secondString = firstString;
firstString = "Goodbye World!";

In the first two lines of code, two variables are declared, firstString and secondString. At this point, two memory areas have been set aside for storing data. The contents of these two variables are null, meaning that their data values are undefined.

In the third line, the text string "Hello World" is assigned to variable firstString. In the next line, the value stored in firstString is assigned to variable secondString. That is, the data value "Hello World" that is sitting in variable firstString is copied into variable secondString. At this point, both variables contain the text string "Hello World". In the last line of code, the text string "Goodbye World" is assigned to variable firstString. The data value "Hello World" is replaced by the value "Goodbye World".

Two important points: (1) When the contents of a variable is assigned to a different variable, it is copied from the source into the destination variable; it is not moved from the source to the destination variable leaving the source variable blank, or null. (2) When a data value is assigned to a variable, it replaces the current contents of the variable with the new value. These operations are illustrated below.

Computer Memory:

var firstString;
var secondString;

Figure 2-5. Assigning variables to variables.

TOP | NEXT: JavaScript Functions