The first element in an array corresponds to index 0. Each subsequent element's index corresponds to the element's distance from the first element.
Consider the following scenario. I have an array consisting of the following elements, in order: "California", "Wyoming", "Vermont", "Wisconsin".
The elements are indexed as such: 0 -- "California" 1 -- "Wyoming" 2 -- "Vermont" 3 -- "Wisconsin"
Here we see the use of square brackets again. An element can be retrieved by the name of the array, followed by the index surrounded by square brackets. See the code snippet below for an example.var myStates = ["California", "Wyoming", "Vermont", "Wisconsin"];
print(myStates[0] + " is 3 thousand miles from " + myStates[2] + ".");
This code produces the following output:
California is 3 thousand miles from Vermont.
var arr = ["cat"];
print(arr[1]);
produces the following output:
undefined
On most other programming platforms, you will encounter a compiler error that notifies you that you are attempting to retrieve an element for an invalid index.