Team LiB   Previous Section   Next Section

1.3 Data Types

JavaScript supports three primitive data types: numbers, booleans, and strings; and two compound data types: object and arrays. In addition, it defines specialized types of objects that represent functions, regular expressions, and dates.

1.3.1 Numbers

Numbers in JavaScript are represented in 64-bit floating-point format. JavaScript makes no distinction between integers and floating-point numbers. Numeric literals appear in JavaScript programs using the usual syntax: a sequence of digits, with an optional decimal point and an optional exponent. For example:

1
3.14
0001
6.02e23

Integers may also appear in hexadecimal notation. A hexadecimal literal begins with 0x:

0xFF // The number 255 in hexadecimal

When a numeric operation overflows, it returns a special value that represents positive or negative infinity. When an operation underflows, it returns zero. When an operation such as taking the square root of a negative number yields an error or meaningless result, it returns the special value NaN, which represents a value that is not-a-number. Use the global function isNaN( ) to test for this value.

The Number object defines useful numeric constants. The Math object defines various mathematical functions such as Math.sin( ), Math.pow( ), and Math.random( ).

1.3.2 Booleans

The boolean type has two possible values, represented by the JavaScript keywords true and false. These values represent truth or falsehood, on or off, yes or no, or anything else that can be represented with one bit of information.

1.3.3 Strings

A JavaScript string is a sequence of arbitrary letters, digits, and other characters from the 16-bit Unicode character set.

String literals appear in JavaScript programs between single or double quotes. One style of quotes may be nested within the other:

'testing'
"3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"

When the backslash character (\) appears within a string literal, it changes, or escapes, the meaning of the character that follows it. The following table lists these special escape sequences:

Escape

Represents

\b

Backspace

\f

Form feed

\n

Newline

\r

Carriage return

\t

Tab

\'

Apostrophe or single quote that does not terminate the string

\"

Double-quote that does not terminate the string

\\

Single backslash character

\xdd

Character with Latin-1 encoding specified by two hexadecimal digits dd

\udddd

Character with Unicode encoding specified by four hexadecimal digits dddd

The String class defines many methods that you can use to operate on strings. It also defines the length property, which specifies the number of characters in a string.

The addition (+) operator concatenates strings. The equality (==) operator compares two strings to see if they contain exactly the same sequences of characters. (This is compare-by-value, not compare-by-reference, as C, C++, or Java programmers might expect.) The inequality operator (!=) does the reverse. The relational operators(<, <=, >, and >=) compare strings using alphabetical order.

JavaScript strings are immutable, which means that there is no way to change the contents of a string. Methods that operate on strings typically return a modified copy of the string.

1.3.4 Objects

An object is a compound data type that contains any number of properties. Each property has a name and a value. The . operator is used to access a named property of an object. For example, you can read and write property values of an object o as follows:

o.x = 1;
o.y = 2;
o.total = o.x + o.y;

Object properties are not defined in advance as they are in C, C++, or Java; any object can be assigned any property. JavaScript objects are associative arrays: they associate arbitrary data values with arbitrary names. Because of this fact, object properties can also be accessed using array notation:

o["x"] = 1;
o["y"] = 2;

Objects are created with the new operator. You can create a new object with no properties as follows:

var o = new Object( );

Typically, however, you use predefined constructors to create objects that are members of a class of objects and have suitable properties and methods automatically defined. For example, you can create a Date object that represents the current time with:

var now = new Date( );

You can also define your own object classes and corresponding constructors; doing this is documented later in this section.

In JavaScript 1.2 and later, you can use object literal syntax to include objects literally in a program. An object literal is a comma-separated list of name:value pairs, contained within curly braces. For example:

var o = {x:1, y:2, total:3};

See Object (and Date) in the reference section.

1.3.5 Arrays

An array is a type of object that contains numbered values rather than named values. The [ ] operator is used to access the numbered values of an array:

a[0] = 1;
a[1] = a[0] + a[0];

The first element of a JavaScript array is element 0. Every array has a length property that specifies the number of elements in the array. The last element of an array is element length-1. Array elements can hold any type of value, including objects and other arrays, and the elements of an array need not all contain values of the same type.

You create an array with the Array( ) constructor:

var a = new Array( );      // Empty array
var b = new Array(10);    // 10 elements
var c = new Array(1,2,3); // Elements 1,2,3

As of JavaScript 1.2, you can use array literal syntax to include arrays directly in a program. An array literal is a comma-separated list of values enclosed within square brackets. For example:

var a = [1,2,3];
var b = [1, true, [1,2], {x:1, y:2}, "Hello"];

See Array in the reference section for a number of useful array manipulation methods.

1.3.6 Functions and methods

A function is a piece of JavaScript code that is defined once and can be executed multiple times by a program. A function definition looks like this:

function sum(x, y) {
  return x + y;
}

Functions are invoked using the ( ) operator and passing a list of argument values:

var total = sum(1,2);  // Total is now 3

In JavaScript 1.1, you can create functions using the Function( ) constructor:

var sum = new Function("x", "y", "return x+y;");

In JavaScript 1.2 and later, you can define functions using function literal syntax, which makes the Function( ) constructor obsolete:

var sum = function(x,y) { return x+y; }

When a function is assigned to a property of an object, it is called a method of that object. Within the body of a method, the keyword this refers to the object for which the function is a property.

Within the body of a function, the arguments[ ] array contains the complete set of arguments passed to the function. See Function and Arguments in the reference section.

1.3.7 null and undefined

There are two JavaScript values that are not of any of the types described above. The JavaScript keyword null is a special value that indicates "no value". If a variable contains null, you know that it does not contain a valid value of any other type. The other special value in JavaScript is the undefined value. This is the value of uninitialized variables and the value returned when you query object properties that do not exist. In JavaScript 1.5, there is a pre-defined global variable named undefined that holds this special undefined value. null and undefined serve similar purposes and the == operator considers them equal; if you need to distinguish between them, use the === operator.

    Team LiB   Previous Section   Next Section