ECMA-262 Core: JavaScript Arrays



Navigation Aids -- This Page        Navigation Aids -- This Topic        Navigation Aids -- This Site







Introduction And Review

We cover arrays from an object perspective at this link, Array Class. Through the Array Class, all arrays have access to the methods and properties of the class. Our discussion here is more general in scope where we describe the basics of JavaScript's arrays.

An array represents a composite data type. A composite type, sometimes called a reference type, is a collection of data values. The array itself is given a name at the time of its declaration. The data values of an array are referenced by the array name plus an index number. The index number represents a position in an array's set of data values. Each position in the array is called an element. The data contained in an element can be a primitive type, composite type or an expression. Note that a given element in an array can actually be another array, thusly, we can build multidimensional arrays. Creating an array is a two step process:

  1. the array declaration
  2. the array initialization

The array declaration can be accomplished using two approaches.

  1. Use the Array Class Constructor and Instantiate an Object of the Array Class type
  2. Use the Array Literal

By definition, a literal always involves initialization. Thus, the literal statement performs both the declaration and initialization in one statement. By contrast, the Array Class constructor actually has three syntactical options at declaration:

  1. name the array (declare)
  2. name the array and specify the number of elements
  3. name the array and assign all element values (initialize)


Creating Simple Arrays

This section will illustrate array creation examples using the Array Class constructor. A subsequent section entitled "The Array Literal" will provide illustrations using the Array literal.

To create, that is, to declare and instantiate, an Array object: var safeColors = new Array( ); // create a new object instance of the Array Class type Here we use the Array Class constructor, Array ( ), along with the new operator to instantiate a new object, safeColors. The new instance, safeColors, is now a reference type variable of the Array class type. It has access to all of the methods of the Array class. However, we have not initialized the object yet.

The Array class constructor allows a variation to the above: var safeColors = new Array(216); // create a new object instance and specify the number of elements



Initialize the Array

If you already know the appropriate values of all or some of the elements in the new Array object, you can specify these values in your declaration statement: var safeColors = new Array("#000000", "#000033", "#000066"); // populate the first three elements At this point, the array has three elements. The length property now equates to three.

We are allowed to use the bracket operator and populate our array as follows: // create a new object instance of the Array Class type var safeColors = new Array( ); safeColors[0] = "#000000"; // make 1st element black safeColors[215] = "#ffffff"; // make last element white We have only populated two elements, however because of how we specified the last statement, the length property of the array is now: (safeColors.length = 216). All element except the first and last have a value of "undefined".

The size of an array will change dynamically depending on the activity. Elements can be added, removed or changed. See "The Dynamics of an Array".



The Array Literal

The array declaration and initialization can be performed with one Array literal statement: var safeColors = ["#000000", "#000033", "#000066"]; // populate the first three elements The Array literal syntax has these qualities:



The Array Element Values

We noted above that the values assigned to an array element can be of any type (both primitive and composite). Furthermore, because JavaScript is weakly typed, any given array can have any and all varieties of data types. The following table provides a brief review of these types and the syntax used to initialize an element of the type using literals.


Data Types Available to Array Elements
Type Group Unique Syntax Possible Values Examples Using Literals
footnote a float is not a unique data type but is a variation of the number data type
String Primitive quotes Character Set for Strings var aRay = ["mouse", "keyboard", "CRT"]
Number Primitive none Integers: whole numbers var aRay = [22,-8,0,300033]
Float Primitive none Floats: have decimal point var aRay = [22.3,-8.99,0.1,3000.33]
Boolean Primitive none true or false var aRay = [false, true, true, true]
Function Composite see note 01 below A JavaScript Function var aRay =
[
function(x,y) { return x*y; }, //index 0
function(x,y) { return x+y; } //index 1
]
Object Composite see note 02 below A JavaScript Object var aRay =
[
{fname: "Fritz",
lname: "Fry",
add1: "12345 S. Street",
city: "Town",
state: "CA",
zip: null}, //index 0

{fname: "Small",
lname: "Fry",
add1: "12345 N. Ave",
city: "City",
state: "CA",
zip: null} //index 1
]
Array Composite see note 03 below A JavaScript Array var aRay =
[
[1,2,3], //index 0
["4","5","6"], //index 1
[true, true, false] //index 2
]
All Both n/a All Types var aRay =
[
[1,2,3],
//index 0 is another array

false,
// index 1 is a boolean

134087,
// index 2 is a number

function(x,y) { return x*y; },
// index 3 is a function

"you could make a database",
// index 4 is a string

{fname: "French",
lname: "Fry",
add1: "9876 N. Ave",
city: "City",
state: "CA",
zip: 93063}
// index 5 is an object
]



Note 01: The function literal begins with the function keyword. Following the keyword, the function literal consists of a comma separated list of parameter names that are all enclosed by a set of parentheses. This is followed by the function body statements enclosed by a set of curly braces.

Note 02: The object literal consists of property specifications, each separated by commas and all enclosed by a set of curly braces. Each property specification consists of the property name followed by a colon and finally the property value.

Note 03: The Array literal consists of a comma separated list of values that are all enclosed by a set of square brackets.



Contrast Index and Element

The array element pertains to a member of an array. The array index is an integer used to access an element. Each element of an array is assigned an integer that can be used as the array index. The index of the first element in an array is zero. The index number along with the array name and the bracket operator gives access to a given element in the array. The position of the last element in an array is equal the value of the Array.length property. The index number of the last element of an array is the number that equates to the Array.length - 1. The relative number of an element's index is always offset by -1 when compared to the element's position.



Accessing an Array

The elements of an array are accessed with the bracket, [ ], operator. The operand inside the brackets must evaluate to an integer and represents the index of the desired element to be accessed. The bracket operator takes two operands. The operand to the left of the bracket operator is the array operand and it represents the name of the array. The second operand ( goes between the brackets ) is an integer operand. var aRay = [22,-8,0,300033];// declare an array var iElement = aRay[1];// access 2nd element, returns -8



The Dynamics of an Array

With some languages such as Java, the number of elements of an array must be specified when the array is declared. The JavaScript array can be a dynamic data type. Elements need not be specified at declaration and elements can be added, changed and removed at any time. Here, we show how this is accomplished. We access the elements of an array with the bracket operator. Given we have an array declared and initialize as: // create a new object instance of the Array Class type var safeColors = new Array( ); safeColors[0] = "#000000"; safeColors[1] = "#000033"; safeColors[2] = "#000066"; safeColors[3] = "#000099"; safeColors[4] = "#0000cc"; safeColors[5] = "#0000ff"; This array has six elements, its length is six and the index of the last element is five.

To add a value to the 11th index: safeColors[11] = "#0033ff"; What becomes of the positions that were skipped over (index values 6 thru 10)?? The interpreter will assign a value of "undefined" to these elements, however, they will not take up space in memory. The length of the array becomes 12.

To change values to the 6th thru 11th indexes: safeColors[11] = "#0033FF"; safeColors[10] = "#0033CC"; safeColors[9] = "#003399"; safeColors[8] = "#003366"; safeColors[7] = "#003333"; safeColors[6] = "#003300";

Note that the Array class has methods that will alter the elements of an array object.



The Multidimensional Array

JavaScript allows data values of an array to be of any data type. A data value can be of a primitive type or a composite data type. When we specify an array element's data value as an array, we have created a two-dimensional array. To access a two-dimensional array, we use two sets of square brackets ([ ] [ ]). The first set is for the outer array and the second set is for the inner array. We can build an array with any number of dimensions, however, keeping track of the data becomes harder with each dimension. With each additional dimension, we add another set of square brackets for access.

A multidimensional array is an array that contains another array. The weakly typed JavaScript data types allow any and all types to be represented as a data value in an array's element. The most common multidimensional array is the two-dimensional array. We can best think of a two-dimensional array as a table where the outer array represents the rows and the inner array represents the columns. For illustrational purposes, our two-dimensional array will be represented by a ticktacktoe puzzle result:

var ticktacktoe = new Array(3);// rows ticktacktoe[0] = new Array(3);// cols in first row ticktacktoe[1] = new Array(3);// cols in second row ticktacktoe[2] = new Array(3);// cols in third row // done with declaration, now populate each square (X wins) ticktacktoe[0][0] = "X";// row 1, col 1 ticktacktoe[0][1] = "O"; ticktacktoe[0][2] = "O"; ticktacktoe[1][0] = "O"; ticktacktoe[1][1] = "X"; ticktacktoe[1][2] = "X"; ticktacktoe[2][0] = "X"; ticktacktoe[2][1] = "O"; ticktacktoe[2][2] = "X";// row 3, col 3

The first set of square brackets represent the row while the second set represents the columns within each row. We could have accomplished the above with one statement: var ticktacktoe = new Array([X,O,O],[O,X,X],[X,O,X]); OR var ticktacktoe = [[X,O,O],[O,X,X],[X,O,X]];// the Array literal

We can build the array structure (the declaration) with a loop. When you have many rows but don't know the values needed to populate the structure, a for loop can save you from writing a lot of statements. Our pretend two-dimensional array has 100 rows with three columns per row: var pretend = new Array(100);// 100 rows for( var i = 0; i < pretend.length; i++) {     pretend[i] = new Array(3); }



The Associative Array

An associative array is an unordered collection of key-value pairs. Rather than access an array element with an index, elements in an associative array are accessed using a string known as a key. Each key of the array must be unique. Associative arrays are also known as a hash. Because each value of the hash has an associated key, hashes will take more memory space than a regular indexed array. The advantage to a hash data structure is that they provide for speedy lookup capabilities. Often a value can be located with one operation rather than using a looping structure required for an indexed array.

var romanNumerals = new Array();    romanNumerals["one"] = "I";    romanNumerals["two"] = "II";    romanNumerals["three"] = "III"; alert(romanNumerals["three"]);//returns III

Summary of the Array Class

Recall that all JavaScript data types have an associated class. The defining source of an Array object of the Array class type can be the Array constructor or the Array literal statement. Array objects instantiated from the Array class have access to the methods and properties of the Array class. To use any given method or property, we associate the object name to the desired method with the dot operator. The Array Class along with it's constructors, methods and properties are all presented in our section dedicated to objects. We give a summary of the Array class methods and the Array.length property here. Take the links for more detail.

• Array.length Property:
This property returns the number of elements in an array. The Array.length property is perfect to use in a for loop's conditional expression to terminate the iteration through an array's elements at EOA (end of the array). The largest possible value of the Array.length property is 232-1. The Array.length property is a read/write value. You can alter the Array.length property value and effect the number of elements allocated to an array:
  • Increase the Array.length value: when you increase the Array.length value from its current size, new undefined elements are added to EOA to reflect the larger size.
  • Decrease the Array.length value: when you decrease the Array.length value from its current size, the array is truncated to the new length. These truncated elements are eliminated from EOA and there values are lost.
The Array.length property remains at zero when an array is declared but not initialize. The Array.length property is automatically updated as value are added to an array via the bracket operator.
• Array.concat( ) Method:
var aRay = [1,2,3]; var bRay = aRay.concat(4,5); Description: this method will concatenate new element values to an existing Array object (the base array) to make a new Array object. The original base array is unaltered. The new concatenated element values are added to EOA.
Methods Argument(s): represent new elements each separated by a comma. The new elements do not need to be of the same data type as the base array.
Method Returns: a new array.
Our Example: Our argument consists of two new elements. These elements, (4,5), are concatenated to the existing array's element (1,2,3) to create a new array, that is: //aRay == [1,2,3] remains unchanged //bRay == [1,2,3,4,5]

• Array.join( ) Method:
var aRay = [1,2,3,4]; var bString = aRay.join(": "); Description: this method converts all elements of an array to strings, then the individual strings are joined to form one single string which serves as the methods return value.
Methods Argument(s): the optional argument is a string that designates the syntax that will separate the elements in the resulting string. The default separator is the comma.
Method Returns: a string.
Our Example: Our argument consists of a colon and a blank to act as the element separator in the resulting string, that is: //aRay == [1,2,3,4] //bString == "1: 2: 3: 4: "

• Array.pop( ) Method:
var aRay = [1,2,3]; var bVar = aRay.pop( ); Description: this method will delete the last element from EOA. This method modifies the array directly, returns same element and decrements the Array.length by one.
Methods Argument(s): none
Method Returns: the last element of the array.
Our Example: The last element (3) is deleted from aRay, the length of aRay is decremented by one and the deleted element is returned to bVar, that is: //aRay == [1,2] //bVar == 3 //aRay.length == 2

• Array.push( ) Method:
var aRay = [1,2,3]; bLength = aRay.push(4,5); Description: this method will append its arguments to the EOA. This method modifies the array directly and returns the new length of the modified array.
Methods Argument(s): represent new elements each separated by a comma that are to be append to the EOA.
Method Returns: the new length.
Our Example: The two new argument values are appended to the existing array. The existing array is modified, that is: //aRay == [1,2,3,4,5] //bLength == 5

• Array.reverse( ) Method:
var aRay = [1,2,3]; aRay.reverse( ); Description: the Array.reverse( ) method alters the base array. The elements of the specified array are rearranged into reverse order.
Methods Argument(s): none
Method Returns: none
Our Example: the specified array had its elements reversed, that is: //aRay == [3,2,1]

• Array.shift( ) Method:
var aRay = [1,2,3]; var bVar = aRay.shift( ); Description: this method will remove the first element (leftmost) of the array. This same element is returned. All subsequent elements of the array are shifted left one position. The Array.length is reduced by one.
Methods Argument(s): none
Method Returns: the element that was shifted out of the array.
Our Example: The first element (1) is shifted out of the array and returned. The vacancy is filled by a shift to the left of the remaining elements, that is: //aRay == [2,3] //bVar == 1 //aRay.length == 2

• Array.slice( ) Method:
var aRay = [9,8,7,6,5,4]; var bRay = aRay.slice(3,5); Description: this method will capture elements from the base array as determined by the start argument and the end argument. The start and end arguments are index values. The slice begins with the start argument and runs until the end argument minus one. The return array contains the element that were sliced.
Methods Argument(s): Two arguments are possible. Both represent an index in the base array. The start argument indicates the start of the slice and the end argument indicates the end of the slice.
Method Returns: a new array that contains the elements sliced from the base array.
Our Example: the element representing the 3rd and 4th indexes were sliced form the base array, that is: //aRay == [9,8,7,6,5,4] //bRay == [6,5]

• Array.sort( ) Method:
var aRay = [9,8,7,6,5,4]; aRay.sort(); Description: this method will reorder the elements of an array in place. When an argument is not specified, the array is sorted alphanumerically.
Methods Argument(s): an optional function that can control the order of the sort.
Method Returns: a reference to the reordered array.
Our Example: the elements in our array were sorted in alphanumeric order, that is: //aRay == [4,5,6,7,8,9]

• Array.splice( ) Method
var aRay = [1,2,3,4]; var bRay = aRay.splice(1,2,9); Description: this method will remove elements from the base array, these same elements are returned in the form of an array, and optionally, values can be specified as replacement elements for those elements removed.
Methods Argument(s): three arguments are possible; start determines starting index, count determines delete count and value provides optional replacement values.
Method Returns: another array reflecting the elements removed.
Our Example: index number (1 & 2) were removed from aRay and there values (2 and 3) were returned to bRay, also value 9 was inserted where the other elements were removed, that is: //aRay == [1,9,4] //bRay == [2,3]

• Array.toLocalString( ) Method:
var aRay = [1,2,3,4,5]; var bString = aRay.toLocalString(); Description: this method will converts all elements to localized string representation and then returns a single string after concatenating the individual strings. The separator used in the return string is local specific. The base array remains unchanged.
Methods Argument(s): none
Method Returns: a string.
Our Example: each numeric value in aRay was converted to a string, then all strings were joined to form the returned string, that is: //aRay == [1,2,3,4,5] //bString == "1,2,3,4,5"//separator is local specific, we used a comma

• Array.toString( ) Method:
//aRay == ["white", "blue", "red"] var bString = aRay.toString(); Description: this method will converts all elements to a string and then returns a single string after concatenating the individual strings. The separator used in the return string is a comma. The base array remains unchanged.
Methods Argument(s): none
Method Returns: a string
Our Example: the strings of aRay were joined and returned as a single string, that is: //aRay == ["white", "blue", "red"] //bString == "white,blue,red"

• Array.unshift( ) Method:
var aRay = [1,2,3]; aRay.unshift(4,5); Description: this method will insert the new elements specified as arguments at the beginning of the array. The array is altered in place. All existing elements are shifted right. The method returns the new length of the modified array.
Methods Argument(s): represent new elements each separated by a comma that are to be inserted at the top (beginning) of the array.
Method Returns: the new length of the altered array.
Our Example: we inserted two new elements at the beginning of the array, that is: //aRay == [4,5,1,2,3] //aRay.length == 5



Additional Comments on Arrays



• The constructor with a single numeric argument:
var safeColors = new Array(216); This line of code does not initialize the safeColors array. It could be interpreted that the first element (of index zero) is being initialized to a numeric "216". However, the Array class constructor will interpret this declaration to allocate 216 elements to the array. At this point, the values of the 216 elements will be "undefined". The safeColors.length will equate to 216. Be aware that some older versions of Netscape do not recognize this third version of the Array class constructor and thusly, the Array.length becomes one and the first element of index zero becomes the argument specified.

• Removing elements with the delete operator:
The delete operator does not remove the element from an array. It will set the element's value to "undefined", but the Array.length property remains unchanged.

• EOA:
EOA is an acronym we use in place of "end of array".

• A FIFO Queue:
We typically build arrays from left to right. Although we can manage a queue in either direction, our example will be from left to right. A FIFO queue is a first in first out queue. In our left to right scenario, the first item in sits to the far right. This item was added to the array first and is now at EOA. Managing our FIFO queue can be orchestrated using the Array Class methods. We use the Array.unshift() method to add additional elements at the front of the queue. The Array.pop() method will remove the last element (first in) from EOA.

• A LIFO Queue:
Although we can manage a queue in either direction, our example will be from left to right. A LIFO queue means the last in item is to be the first item retrieved. The last in item of an array (our left to right example) is the leftmost element. We use the Array.unshift() method to add elements at the left. The Array.shift() method will remove an element from the left (first out) and all remaining elements shift left.



Top            

Rx4AJAX        About Us | Topic Index | Contact Us | Privacy Policy | 2008 This Site Built By PPThompson