JavaScript’s data types are broken down into primitive and composite types. Primitive types hold simple values and are passed to functions by value. Composite types hold heterogeneous data (primitive and/or composite values) and are passed to functions by reference. JavaScript is weakly typed.
Five primitive types are defined, only three of which can hold useful data. These data types are summarized in Table A-7.
Type |
Description |
Values |
Literal Syntax |
---|---|---|---|
Takes on one of two values. Used for on/off, yes/no, or true/false values and conditionals. |
true, false |
true, false |
|
null |
Has only one value. Indicates the absence of data, for example, placed in unspecified function argument. |
null |
null |
Includes both integer and floating-point types. 64-bit IEEE 754 representation. Integer ops usually carried out using only 32 bits. |
Magnitudes as large as ±1.7976ґ10308 and as small as ±2.2250ґ10-308. Integers considered to have a range of 231–1 to –231 for computational purposes. |
Decimal values (including exponent), hexadecimal, octal |
|
Zero or more Unicode (Latin-1 prior to Netscape 6/IE4) characters. |
Any sequence of zero or more characters. |
Single- or double-quote delimited |
|
undefined |
Has only one value and indicates that data has not yet been assigned. For example, undefined is the result of reading a non-existent object property. |
undefined |
undefined (IE5.5+/NS6+/ECMA3) as a property of Global. Previously not available |
JavaScript/ECMAScript defines a select number of numeric constants, which are detailed in Table A-8. The Math object, discussed in Chapter 7 and Appendix B, also includes a variety of useful values such as Math.PI.
Numeric Constant |
Description |
---|---|
Infinity |
Infinity (property of Global) |
NaN |
Not a number (property of Global) |
Number.NEGATIVE_INFINITY |
Negative infinity |
Number.POSITIVE_INFINITY |
Positive infinity |
Number.NaN |
Not a number |
Number.MAX_VALUE |
Maximum representable value, usually 1.7976931348623157e+308 |
Number.MIN_VALUE |
Minimum representable value, usually 5e–324 |
JavaScript also defines a variety of string type–related special values, which are defined in Table A-9. These string escape codes are used for formatting strings.
Escape Code |
Value |
---|---|
\b |
Backspace |
\t |
Tab (horizontal) |
\n |
Linefeed (newline) |
\v |
Tab (vertical) |
\f |
Form feed |
\r |
Carriage return |
\" |
Double quote |
\' |
Single quote |
\\ |
Backslash |
\OOO |
Latin-1 character represented by the octal digits OOO. The valid range is 000 to 377. |
\xHH |
Latin-1 character represented by the hexadecimal digits HH. The valid range is 00 to FF. |
\uHHHH |
Unicode character represented by the hexadecimal digits HHHH. |
Type conversion is automatically carried out in JavaScript. Tables A-10, A-11, A-12, A-13, and A-14 show the conversion rules when data is automatically converted to one type or another. Automatic conversion happens very often when using relational operators discussed later in the section. It is also possible to force type conversion using a variety of built-in methods summarized in Table A-15.
Boolean Converted To |
Result |
---|---|
1 if true, 0 if false |
|
“true” if true, “false” if false |
|
object |
A Boolean object whose value property is true if true, or false if false |
Null Converted To |
Result |
---|---|
False |
|
0 |
|
“null” |
|
object |
Impossible. A TypeError exception is thrown. |
Number Converted To |
Result |
---|---|
False if value is 0 or NaN, otherwise true |
|
String representing the number (including special values) |
|
object |
A Number object whose value property is set to the value of the number |
String Converted To |
Result |
---|---|
False if given the empty string (i.e., a string of length zero), true otherwise. |
|
Attempts to parse the string as a numeric literal (e.g., “3.14” or “-Infinity”) to obtain the value. If parsing fails, NaN. |
|
object |
A String object whose value property is set to the value of the string. |
Undefined Converted To |
Result |
---|---|
False |
|
NaN |
|
“undefined” |
|
object |
Impossible. A TypeError exception is thrown. |
Description |
Details |
---|---|
Number methods |
toExponential(), toFixed(), toPrecision() for conversion to numbers |
Global methods |
parseInt(), parseFloat() for converting strings to numbers |
Object methods |
toString(), valueOf() (retrieves the primitive value associated with the object) |
Constructors |
The most generic composite type from which all other composite types are derived is the Object. An Object is an unordered set of properties that may be accessed using the dot operator:
object.property
equivalently:
object["property"]
In case the property is a function (method), it may be invoked as
object.method()
Static (or class) properties are accessed through the constructor:
Object.property
Objects are created using the new operator in conjunction with a special constructor function.
[var] instance = new Constructor(arguments);
Once an instance of an object is created, setting properties is similar to a standard assignment,
instance.property = value;
and accessed using the standard dot (.) operator.
instance.property
The this statement refers to the “current” object, that is, the object inside of which this is invoked. Its syntax is
this.property
and it is typically used inside of a function (for example, to access the function’s length property) or inside of a constructor in order to access the new instance being created. Used in the global context, this refers to the current Window.
Table A-16 lists the built-in objects found in ECMAScript-based languages such as JavaScript. These objects are part of the language itself, as opposed to host (or browser) objects that are provided by the browsers. Note that you cannot instantiate Global or Math objects. The Global object is not even explicitly addressable. It is defined as the outermost enclosing scope (so its properties are always addressable). Chapter 7 as well as Appendix B provide details and examples of these objects and their methods and properties.
Object |
Description |
---|---|
Provides an ordered list data type and related functionality |
|
Object corresponding to the primitive Boolean data type |
|
Facilitates date- and time-related computation |
|
Error |
Provides the ability to create a variety of exceptions (and includes a variety of derived objects such as SyntaxError) |
Function |
Provides function-related capabilities such as examination of function arguments |
Provides universally available functions for a variety of data conversion and evaluation tasks |
|
Provides more advanced mathematical features than those available with standard JavaScript operators |
|
Object corresponding to the primitive number data type |
|
Object |
Generic object providing basic features (such as type-explicit type conversion methods) from which all other objects are derived |
RegExp |
Permits advanced string matching and manipulation |
Object corresponding to the primitive string data type |
The Global object in particular contains a variety of useful utility properties and methods. Aspiring JavaScript programmers should become very familiar with the features of Global summarized in Table A-17.
Property |
Description |
---|---|
decodeURI(encodedURI) |
URI-decodes the string encodedURI and returns the result |
decodeURIComponent(uriComponent) |
URI-decodes the encodeURIComponent-encoded string uriComponent and returns the result |
encodeURI(string) |
URI-encodes the string string and returns the result |
encodeURIComponent(string) |
URI-encodes the string string and returns the result |
escape(string) |
URL-encodes string and returns the result |
eval(x) |
Executes the string x as if it were JavaScript source code |
Infinity |
The special numeric value Infinity |
isFinite(x) |
Returns a Boolean indicating whether x is finite (or results in a finite value when converted to a number) |
isNaN(x) |
Returns a Boolean indicating whether x is NaN (or results in NaN when converted to a number) |
NaN |
The special numeric value NaN |
parseInt(string [, base]) |
Parses string as a base-base number (10 is the default unless string begins with “0x”) and returns the primitive number result (or NaN if it fails) |
parseFloat(string) |
Parses string as a floating-point number and returns the primitive number result (or NaN if it fails) |
undefined |
Value corresponding to the primitive undefined value (this value is provided through Global because there is no undefined keyword) |
unscape(string) |
URL-decodes string and returns the result |
JavaScript supports arrays both in an object and literal style. Array literals are used with the following syntax (the brackets are “real” brackets and do not indicate optional components):
[element1, element2, …]
Each elementN is optional, so you use an array with “holes” in it, for example:
var myArray = ["some data", , 3.14, true ];
You can also use the Array() constructor:
var variable = new Array(element1, element2, …);
but be aware that if only one numeric argument is passed, it is interpreted as the initial value for the length property. It is important to note the close relationship between arrays and objects in JavaScript. Object properties can be accessed not only as objectName.propertyName but as objectName['propertyName']. However, this does not mean that array elements can be accessed using an object style; arrayName.0 would not access the first element of an array.
Function literals are used with the following syntax,
function ([ args ]) { statements }
where args is a comma-separated list of identifiers for the function arguments and statements is zero or more valid JavaScript statements.
Although not strictly a literal, you can also use the Function() constructor:
new Function(["arg1", ["arg2"], … ,] "statements");
The argN’s are the names of the parameters the function accepts and statements is the body of the function. For example:
myArray.sort(new Function("name", "alert('Hello there ' + name)"));
Object literals are used with the following syntax:
{ [ prop1: val1 [, prop2: val2, … ]] }
For example:
var myInfo = { city: "San Diego", state: "CA" , province: null, sayHi = function() { alert("Hello there") } }
Regular expression literals (actually RegExp literals) have the following syntax:
/exp/flags
where exp is a valid regular expression and flags is zero or more regular expression modifiers (e.g., “gi” for global and case-insensitive).
Although not strictly a literal, you can use the RegExp() constructor:
new RegExp("exp" [, "flags"])