JavaScript Data Types

Data Types (JavaScript)
JavaScript - Internet Explorer 9
Other Versions

    * Windows Scripting 5.8

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

In JavaScript, there are three primary data types, two composite data types, and two special data types.
Primary Data Types

The primary (primitive) data types are:

    *

      String
    *

      Number
    *

      Boolean

Composite Data Types

The composite (reference) data types are:

    *

      Object
    *

      Array

Special Data Types

The special data types are:

    *

      Null
    *

      Undefined

String Data Type

A string value is a chain of zero or more Unicode characters (letters, digits, and punctuation marks) strung together. You use the string data type to represent text in JavaScript. String literals can be included in your scripts by enclosing them in matching pairs of single or double quotation marks. Double quotation marks can be contained within strings surrounded by single quotation marks, and single quotation marks can be contained within strings surrounded by double quotation marks. The following are examples of strings:
VB
C#
C++
F#
JScript
Copy

This language is not supported or no code example is available.

Notice that JavaScript does not have a type to represent a single character. To represent a single character in JavaScript, you create a string that consists of only one character. A string that contains zero characters ("") is an empty (zero-length) string.

JavaScript provides escape sequences that you can include in strings to create characters that you cannot type directly. For example, \t specifies a tab character. For more information, see Special Characters (JavaScript).
Number Data Type

In JavaScript, there is no distinction between integer and floating-point values; a JavaScript number can be either (internally, JavaScript represents all numbers as floating-point values).
Integer Values

Integer values can be positive whole numbers, negative whole numbers, and 0. They can be represented in base 10 (decimal), base 16 (hexadecimal), and base 8 (octal). Most numbers in JavaScript are written in decimal.

You denote hexadecimal ("hex") integers by prefixing them with a leading "0x" (zero and x|X). They can contain digits 0 through 9, and letters A through F (either uppercase or lowercase) only. The letters A through F are used to represent, as single digits, 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is equivalent to 16.

You denote octal integers by prefixing them with a leading "0" (zero). They can contain digits 0 through 7 only. A number that has a leading "0" and contains the digits "8" and/or "9" is interpreted as a decimal number.

Both hexadecimal and octal numbers can be negative, but they cannot have a decimal portion, and they cannot be written in scientific (exponential) notation.
Note Note

Starting in Internet Explorer 9 (Internet Explorer 9 Standards mode), the parseInt function does not treat a string that has a prefix of "0" as octal. When you are not using the parseInt function, however, strings with a prefix of "0" can still be interpreted as octal.
Floating-point Values

Floating-point values can be whole numbers with a decimal portion. Additionally, they can be expressed in scientific notation. That is, an uppercase or lowercase "e" is used to represent "ten to the power of". JavaScript represents numbers using the eight byte IEEE 754 floating-point standard for numerical representation. This means you can write numbers as large as 1.79769x10308, and as small as 5x10-324. A number that contains a decimal point and that has a single "0" before the decimal point is interpreted as a decimal floating-point number.

Notice that a number that begins with "0x" or "00" and contains a decimal point will generate an error. Here are some examples of JavaScript numbers.

Number
   

Description
   

Decimal Equivalent

.0001, 0.0001, 1e-4, 1.0e-4
   

Four equivalent floating-point numbers.
   

0.0001

3.45e2
   

A floating-point number.
   

345

45
   

An integer.
   

45

0378
   

An integer. Although this looks like an octal number (it begins with a zero), 8 is not a valid octal digit, so the number is treated as a decimal.
   

378

0377
   

An octal integer. Notice that although it only appears to be one less than the number above, its actual value is quite different.
   

255

0.0001
   

A floating point number. Even though this begins with a zero, it is not an octal number because it has a decimal point.
   

0.0001

00.0001
   

This is an error. The two leading zeros mark the number as an octal, but octals are not allowed a decimal component.
   

N/A (compiler error)

0Xff
   

A hexadecimal integer.
   

255

0x37CF
   

A hexadecimal integer.
   

14287

0x3e7
   

A hexadecimal integer. Notice that the 'e' is not treated as exponentiation.
   

999

0x3.45e2
   

This is an error. Hexadecimal numbers cannot have decimal parts.
   

N/A (compiler error)

Additionally, JavaScript contains numbers with special values. These are:

    *

      NaN (not a number). This is used when a mathematical operation is performed on inappropriate data, such as strings or the undefined value
    *

      Positive Infinity. This is used when a positive number is too large to represent in JavaScript
    *

      Negative Infinity. This is used when a negative number is too large to represent in JavaScript
    *

      Positive and Negative 0. JavaScript differentiates between positive and negative zero.

Boolean Data Type

Whereas the string and number data types can have a virtually unlimited number of different values, the Boolean data type can only have two. They are the literals true and false. A Boolean value is a truth-value — it expresses the validity of a condition (tells whether the condition is true or not).

Comparisons you make in your scripts always have a Boolean outcome. Consider the following line of JavaScript code.


This language is not supported or no code example is available.

Here, the value of the variable x is tested to see if it is equal to the number 2000. If it is, the result of the comparison is the Boolean value true, which is assigned to the variable y. If x is not equal to 2000, then the result of the comparison is the Boolean value false.

Boolean values are especially useful in control structures. Here, you combine a comparison that creates a Boolean value directly with a statement that uses it. Consider the following JavaScript code sample.


This language is not supported or no code example is available.

The if/else statement in JavaScript performs one action if a Boolean value is true (in this case, z = z + 1), and an alternate action if the Boolean value is false (x = x + 1).

You can use any expression as a comparative expression. Any expression that evaluates to 0, null, undefined, or an empty string is interpreted as false. An expression that evaluates to any other value is interpreted as true. For example, you could use an expression such as:


This language is not supported or no code example is available.

Note that the above line does not check if x is equal to y + z, since only a single equal sign (assignment) is used. Instead, the code above assigns the value of y + z to the variable x, and then checks if the result of the entire expression (the value of x) is zero. To check if x is equal to y + z, use the following code.


This language is not supported or no code example is available.

For more information on comparisons, see Controlling Program Flow.
Null Data Type

The null data type has only one value in JavaScript: null. The null keyword cannot be used as the name of a function or variable.

A variable that contains null contains "no value" or "no object." In other words, it holds no valid number, string, Boolean, array, or object. You can erase the contents of a variable (without deleting the variable) by assigning it the null value.

Notice that in JavaScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in JavaScript will report null values as being of type Object, not of type null. This potentially confusing behavior is for backwards compatibility.
Undefined Data Type

The undefined value is returned when you use:

    *

      an object property that does not exist,
    *

      a variable that has been declared, but has never had a value assigned to it.

Notice that you cannot test to see if a variable exists by comparing it to undefined, although you can check if its type is "undefined". In the following code example, assume that the programmer is trying to test if the variable x has been declared:


This language is not supported or no code example is available.

Consider comparing the undefined value to null.
Copy

someObject.prop == null;

This comparison is true,

    *

      if the property someObject.prop contains the value null,
    *

      if the property someObject.prop does not exist.

To check if an object property exists, you can use the new in operator:


This language is not supported or no code example is available.

...................................................................................................................................................................


Data Types
main > javascript > core javascript > js data types

These tutorials are about JavaScript and its use for client-side Web programming.
Data Types

data type: a general term to describe categories of values that a program or programming language can make use of

A computer works with values. It manipulates values and produces some kind of result. Depending on the program, it may be limited as to what types of values it can work with. The types of values a program can work with are known as its data types.

JavaScript supports many types of data.

Data types can be broken into two broad categories, primitive and composite.

A primitive data type is a data type that stores a single value, normally a literal of some sort, such as numbers and strings.

A composite data type, for the purposes of JavaScript, is the same thing as an object. It is a data type that can consist of multiple values grouped together in some way. JavaScript treats objects as associative arrays. An associative array is an array that can have its elements associated with names in addition to their numeric index position in the array.

JavaScript also treats functions as objects. This means that functions can be used just like any other variable.
Primitive Data Types

There are three primitive data type of interest to us:

    * numbers
    * strings
    * boolean values

Numbers

Numbers are the easist of the data types to understand. They represent numeric values.

The simplest type of number is an integer.

An integer is a base-10 whole number. In other words, it is a number with no fractional component. JavaScript can handle integer values between 253 and -253. Some JavaScript functions, however, cannot handle extremely large or small numbers, so it is probably a good idea to try to keep your numbers in the range of 231 and -231. Since that is plus or minus 2 trillion, this shouldn't be a problem as long as you are not trying to track the national debt.

All of the following are valid integers.

    * 0
    * -75
    * 10000000
    * 2

Another commonly used type of number is a floating-point number. A floating-point number is a number that is assumed to have a decimal point. The decimal point is the point that floats and gives the data type its name.

Floating-point numbers have a fractional component, even if that fractional component is zero. They can be represented as a real number (integer - decimal point - fractional value) such as in 3.1714, or using exponential notation.

Exponential notation is a number multiplied by ten times the power of some exponent, for instance 3.1714x10-15 (0.0000000000000031714). Exponential notation is usually written with an "e" instead of the "x10", so that JavaScript will know it is a floating-point number and not an equation. This would read as 3.1714e-15.

All of the following are valid floating-point numbers.

    * 5.00
    * 1.3333333333333
    * 1.0e25
    * 7.5e-3

JavaScript stores floating-point numbers in exponential form, storing the number and its exponent. Just to confuse the issue, it also stores integers as floating-point numbers, but this is transparent to you as the programmer and you don't have to worry about it.

Being a computing language, JavaScript also has the ability to handle hexadecimal (four bit) and octal (three bit) numbers. Octal support is newer and is best avoided since older version of JavaScript will think the octal number is a hexadecimal number. All hexadecimal numbers begin with a zero and an X, for instance 0xff0000. Octal numbers, if they are supported, begin with a zero, for instance, 0755. If they are not supported, this notation will be treated as another way of expressing hexadecimal numbers.

JavaScript also has some numeric keyword literals you should know about. These are listed below.

Infinity
    Infinity has the value of infinity, which is to say a number larger than the largest number that JavaScript can represent. Not really infinity, but from a computing perspective, it might as well be.
    There is also the keyword literal -Infinity for the negative infinity.
    As well as keywords, these can be represented as properties of the Number object as Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY.
    Using the number object properties comes from older JavaScript, while the keyword literals were first implemented with JavaScript 1.3. You can test for infinity with the isFinite() function.
NaN
    NaN is the value returned when you try to treat something that is not a number as a number. For instance the results of 7 times "abc" is not a number. The old form of it is Number.NaN. You can test for not-a-number values with the isNaN() function.
Number.MAX_VALUE
    Number.MAX_VALUE represents the largest representable number for JavaScript
Number.MIN_VALUE
    Number.MIN_VALUE represents the small representable non-zero number for JavaScript. In other words as close as JavaScript can get to zero with actually reaching zero.

Strings

A string is sequence of valid characters within a given character set. It is normally used to represent text. A string literal is defined by enclosing it in matching single or double quotes.

If you create a string with nothing in it, it is called an empty string. It is normally created by two quote marks with nothing between them.

Some characters that you may want in a string may not exist on the keyboard, or may be special characters that can't appear as themselves in a string. In order to put these characters in a string, you need to use an escape sequence to represent the character. An escape sequence is a character or numeric value representing a character that is preceeded by a backslash ( \ ) to indicate that it is a special character.

Some escaped characters are as follows:
Escape Sequence     Character
\0     (blackslash zero) The Null character (\u0000). If you've taken COBOL, you may recognize this as COBOL's low-value, used to populate fields with a clearly defined invalid value that tests less than anything else.
\b     Backspace.
\t     Tab. Tabs behave erratically on the Web and are best avoided, but sometimes you need them.
\n     New line (\u0000a). Inserts a line break at the point specified. It is a combination of the carriage return (\r) and the form feed (\f).
\"     Double quote.
\'     Single quote, or an apostrophe, such as in can\'t.
\\     The backslash, since by itself it is a command.
\x99     A two digit number specifying the hexadecimal value of a character in the Latin-1 character set (ASCII).
\u9999     A four digit hecadecimal number specifying a character in the Unicode character set. This is not supported before JavaScript 1.3.
Boolean Values

There are two boolean values, true and false. These are normally the result of a logical comparison in your code that returns a true/false or yes/no result, such as
a == b.
This statment reads: does the value of variable a equal the value of variable b?

If you need to use boolean values in computations, JavaScript will automatically convert true to 1 and false to 0.

The conversion can also work the other way. When testing for the result of a comparison, JavaScript will treat any non-zero value as true, and a zero value as false. JavaScript will also test to false when you test for the existence of something that does not exist.
Composite Data Types

All composite data types can be treated as objects, but we normally categorize them by their purpose as a data type. For composite data types we will look at objects, including some special pre-defined objects that JavaScript provides, as well as functions and arrays. We will look at all of these elements in more detail elsewhere, so we will only touch on them lightly here.
Objects

An object is a collection of named values, called the properties of that object. Functions associated with an object are referred to as the methods of that object.

Properties and methods of objects are referred to with a dot.notation that starts with the name of the object and ends with the name of the property. For instance
image.src.

Normally in objects there are only two nodes, the object and the property, but as we will discover, sometimes the properties can have properties of their own, creating an object tree which you have to specify the path through in the same way you would with a directory tree (except you are using periods instead of slashes).

For instance,
document.form1.namefield.

Objects in JavaScript can be treated as associative arrays. This means that image.src and image['src'] are equivalent. This flexibility has its uses, since this means that you can pass property names as the values of variables.

For instance, this code snippet:
img[iProp] = newImage[iProp];
might exist in a loop that resets the properties of an image one by one.

JavaScript has many predefined objects, such as a Date object and a Math object. These are used much as function libraries are used in a language like C. They contain a collection of useful methods that are predefined and ready for use in any JavaScript code you may write.
Functions

A function is a piece of code, predefined or written by the person creating the JavaScript, that is executed based on a call to it by name.

Any JavaScript that is not inside a function (or is not associated with some even attribute or hyperlink attribute) is executed the moment the Web browser reaches it when first parsing the document. Functions allow execution to be delayed. They also allow for the same piece of code to be re-used many times in the same document, since functions allow the section of code they contain to be referred to by name.

A function is a data type in JavaScript. This is different from many other programming languages. This means that they can be treated as containing values that can be changed.
Arrays

An Array is an ordered collection of data values.

In some programming languages, arrays have very specific limitations. In JavaScript, an array is just an object that has an index to refer to its contents. In other words, the fields in the array are numbered, and you can refer to the number position of the field.

The array index is included in square brackets immediately after the array name. In JavaScript, the array index starts with zero, so the first element in an array would be arrayName[0], and the third would be arrayName[2].

JavaScript does not have multi-dimensional arrays, but you can nest them, which is to say, an array element can contain another array. You access them listing the array numbers starting for the outmost array and working inward. Therefore, the third element (position 2) of or inside the ninth element (position 8) would be arrayName[8][2].

We will be discussing how to create and work with arrays elsewhere.
JavaScript Object Literals

JavaScript also has two keyword literals that it considers to be objects. These are null and undefined.

Something with the value null has no value, which is to say that it does not contain a valid object, array, string, number, or boolean value. It is the value of no value. Normally you assign the value null to something when you want it to have a valid but non-existent value.

Unlike null, undefined is not a keyword. It is a predefined global variable, but it is treated like any other variable. Be careful not to overwrite it. The variable undefined is used to store the value of an undefined variable.

An undefined variable is one that has been named, but does not have a value assigned to it. This means that it is not zero, it is not null, but it is undefined. The reason it is undefined is that even though there is officially no value in there, there is really whatever garbage is still sitting in that location in memory now contained in that variable (computers don't really bother to clean up after themselves when things are deleted, they just actively forget that anything is there). To avoid this problem, JavaScript assigns the value of undefined to a variable until a value is assigned to it. 

0 comments:

Post a Comment