An array is a variable (with a name) that holds many elements of the same type addressed by indices.
Here's how you make an array:
let <name>: <type>[ ] = [<element1>, <element2>, <element3>, ... ];
The above syntax includes declaration and initialization. It also includes information about the type of the array. If we wanted to declare and initialize at the same time while also using type inference, it could look like this:
let <name> = [<element1>, <element2>, <element3, ... ];
Here are some examples:
let myFriends: string[ ] = ["Jim", "Kevin", "Erin"]; let departments = ["sales", "accounting", "reception"];
Let's take a closer look at how arrays work.
An index is the integer used to reference each element in an array.
The first element of an array is located at index 0, the second is at index 1, and so on.
NOTE: the length of an array does not equal the last index! Arrays are "zero-indexed" meaning they start counting indices at 0. So the length of our array will always be the last index + 1.
To show this, a two element array would have the first element at index 0 and the second at index 1. However, since there are 2 elements, the length of the array is 2.
let x: <type> = <array name>[<index number>];
When you access an element, you can assign it to a variable to more easily access it later.
You can also change individual elements in an array without having to create an entirely new array!
<array name>[<index number>] = <new element value>;
// utilizing the myFriends and departments arrays from above // ACCESSING ELEMENT let myBestFriend = myFriends; // myBestFriend will now be "Jim" let bffDept = departments; // bffDept will now be "sales" // REASSIGNING ELEMENTS myFriends = "Pam"; // myFriends is now: ["Jim", "Kevin", "Pam"] departments = "sales"; // departments is now: ["sales", "accounting", "sales"]
A big thing to remember is that since arrays are 0-indexed, meaning the index numbers start with the first one being 0, the last index of an array is the length of the array - 1, or <arrayName>.length - 1
Adding an element onto the end of an array is called appending the element to the array. We do this by using the length of the array to be the next index. Since array indices start at 0, the current length of the array will be the next index that we're adding to the array. Here, we'll do an example appending to the arrays we've been using in the previous examples:
// append onto the arrays myFriends[myFriends.length] = "Creed"; //myFriends.length is 3, so its equivalent to myFriends // myFriends is now ["Jim", "Kevin", "Pam", "Creed"] departments[departments.length] = "quality assurance"; // departments is now ["sales", "accounting", "sales", "quality assurance"]
Here, we're using myFriends.length and departments.length. Using .length gives us the length of the array. Since array indices start at zero, the length will be one more than the last index, so it will be our next empty index.