JavaScript arrays (or lists) take the concept of storage to a whole new level. Unlike regular variables that can store only single values, JavaScript arrays or lists allow us to store a series of data. Since JavaScript arrays are objects, the typeof operator returns the type of arrays as "object".
To define an array, we simply need to keep all the values within square brackets and separate them with commas. Thus, "var arraySimple = ["Rutherford", "Pauling", "Wilkinson"];". An array can be a mix of variable types and can hold both primitive and non-primitive types.
Since arrays are objects, we can also define them using the Array constructor: "var arraySimple = new Array("Rutherford", "Pauling", "Wilkinson");". If you are not familiar with objects and constructors, well, there is nothing to worry about it since we would not be using them a lot! For the time being, it would suffice to remember that a constructor is a function that gets called first when we create an object.
We can reference elements of an array using their index. The indexing is 0-based and so, the first element has an index 0, the second element has an index 1, and so on. Thus, to refer to the first element in the above array, we can use "arraySimple[0]", to access the second element, we can use "arraySimple[1]", etc. Since arrays can have several elements, each array object also has a property named "length" that stores the number of elements present in the array.
Here is an example that defines an array using both of the above methods and prints their value using a for-loop; do not panic -- we would talk about for-loop in the very next section!
<!doctype html> <html> <div id="idDiv"> </div> <script type="text/javascript"> // Get a handle of the div element. var elem = document.getElementById("idDiv"); // Define an array using the "[]" method var arraySimpleA = ["Rutherford", "Pauling", "Wilkinson", 280]; // Print its values. elem.innerHTML += "Printing arraySimpleA (Length " + arraySimpleA.length + "):<br>"; for (var i=0; i < arraySimpleA.length; i++) { elem.innerHTML += "[index: " + i + "] value: " + arraySimpleA[i] + "<br>"; } // Another way to define the same array. var arraySimpleB = new Array("Rutherford", "Pauling", "Wilkinson", 280); // Print its values. elem.innerHTML += "<br>Printing arraySimpleB (Length " + arraySimpleB.length + "):<br>"; for (var i=0; i < arraySimpleB.length; i++) { elem.innerHTML += "[index: " + i + "] value: " + arraySimpleB[i] + "<br>"; } </script> </html>
If we run this example, then we would find similar values for both arrays. Here is what we would see on the browser:
Printing arraySimpleA (Length 4): [index: 0] value: Rutherford [index: 1] value: Pauling [index: 2] value: Wilkinson [index: 3] value: 280 Printing arraySimpleB (Length 4): [index: 0] value: Rutherford [index: 1] value: Pauling [index: 2] value: Wilkinson [index: 3] value: 280