JavaScript Arrays
Arrays can help you to create more sophisticated scripts, by storing multiple values within a single variable.
What is an array?
Arrays are a fundamental part of most programming languages and scripting languages. Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.
For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.
Visualizing Arrays
Arrays can be visualized as a stack of elements.
Array | |
0 | What are JavaScript arrays? |
1 | How to create arrays in JavaScript? |
2 | What are two dimensional arrays? |
Note: Some programming languages start arrays at zero, other start at one. JavaScript arrays start at zero.
Creating Arrays in JavaScript
Most programming languages use similar syntax to create arrays. JavaScript arrays are created by first assigning an array object to a variable name...
then by assigning values to the array...
So, using our prior example, we could write:
Accessing Arrays in JavaScript
You can access an array element by referring to the name of the array and the element's index number.
Displaying Array Elements
The above code displays the second element of the array named faq (JavaScript array index numbers begin at zero). In this case, the value would be How to create arrays in JavaScript?
Modifying the Contents of an Array
You can modify the contents of an array by specifying a value for a given index number:
In this case, the value of the second element of this array would now be How to modify an array?
Two Dimensional Arrays
So far we've only discussed one dimensional arrays. You can also create two dimensional arrays, which can be much more powerful than one dimensional arrays. Two dimensional arrays are covered in the next lesson.