let names = ["Bill", "James", "Larry", "Tim"]
The list of names above is being stored in a variable called names. This allows you to have access to the list in any part of your code depending on the scope or position where the variable is declared. You can access the names in the array by the position number of the items starting from left to right. Do note that positions do not start at 1, but 0 in arrays. You will also need to use bracket notation for the position.
let leader; let names = ["Bill", "James", "Larry", "Tim"] leader = names; //leader is set to Larry
As you can see from the above example, we set the variable leader to be the name Larry from the array by accessing it's position of 2. Again, it would not be 3 because the positions start at 0. What really makes arrays great besides being able to store large amounts of data, are the built in array properties and methods(actions) that let you manipulate the data. I have included a couple in the example below.
let names = ["James", "Bill", "Tim", "Larry"] names.length// returns length of array: 4 names.sort(); //items in array are sorted: ["Bill", "James", "Larry", "Tim"] names.push("Willy");/**item is added to the end of array and the length of array is returned: ["Bill", "James", "Larry", "Tim", "Willy"] length of 5**/ names.pop();//the last item in the array will be removed and the item will be returned: "Willy"
The above are just some of the many methods that you can use on arrays to help manipulate the data in the way that you need. A very good reference for the other arrays methods can be found at w3schools here.
Top comments (0)