JavaScript programming often involves using arrays to store information. For example, the tags that are accessed using the document object are often returned as an array (i.e. from the document.getElementsByName method). However, arrays are also available to JavaScript programmers for their own use - as stacks, queues, or just a place to put information.
As an aside - unlike other languages with a C-like syntax, an array of characters in JavaScript is not the same as a string: the string class has other methods for string processing that have nothing to do with arrays, and the 2 are not interchangeable.
To create an array, code such as the following can be used:
The first line of code creates an array of 100 elements, starting with element 0 and ending with element 99. If the programmer assigns a value to myArray[100] then JavaScript will automatically extend the array.
The other array is created with 3 elements of different types: an array does not necessarily have to contain elements where all the types are the same. There is also an indirect way to create an array:
While this may be useful in certain circumstances, many programmers avoid using this method of creating an array.
To use the JavaScript array as a stack, there are 2 collections of methods:
The following JavaScript application snippet illustrates a stack where elements are manipulated at the end:
To manipulate elements at the start, the following would be used:
These can be combined to emulate a queue.
A queue is similar to a stack except that typically the elements are removed from the opposite end to which they are added. For example, a FIFO queue (First In First Out) can be emulated using unshift and pop:
The other kind of queue, a LIFO (Last In First Out) is the same as a regular stack, in which elements are pushed and poped from the end.
Finally, a JavaScript array can be sorted by using the sort method:
Unless the programmer supplies their own sorting function (i.e. myArray.sort(my_sorting_function)), which must take 2 elements and return -1, 0 and 1 upon comparison, multi-type arrays may not be sorted correctly. This is because the elements will be converted to strings and sorted alphabetically.
There are also some more advanced methods that are available: