Have you read through Mozilla Developer Network’s documentation on arrays? It’s great, but it can be a little overwhelming (especially if you are new to programming and/or arrays). Below, I have written an easy to follow quick start on the array methods I believe are
level 1 that I use most in my programming.
If you are not new to arrays, then click here to skip the Quick Notes for Beginners with Arrays section.
Three Quick Notes for Beginners with Arrays
1) Arrays have an index that starts at 0.
An index is a number assigned to an item as it enters the array. The number can be used to locate an item in the array. (See below.)
c is located at index 2. It is the third item in the list but since an array’s index starts at 0, it is located at position 2.
2) How to declare an array.
Use brackets to declare an array. Use empty brackets when you do not have values for your array yet. The name of my array is
arrayName but you can call your array just about anything (as long as it does not start with a number).
3) Array Values - Strings and Numbers
Items in the array can be strings or numbers. Strings have to be surrounded by single
' or double quotes
" and numbers do not. Yes, you can have both strings and numbers in the same array.
Add Item to end of Array
Push adds the item in parenthesis to the end of the array.
Use case: When you need to add a username to the array of logged in users.
Find Index of Item in Array
If the item you put in parenthesis is in the array,
indexOf will return the index number of the item. If the item you are searching for is not in the variable you specified, then
indexOf will return
Use case: Check if the user is already in your array.
In the example above,
indexOf returns the number
3. To see what
indexOf returned, we logged it to the console using
Remove Item in Array by Index Number
Splice takes two parameters,
Start is the index number of the item to start from, and
deleteCount is how many to delete. For this example, I used
0 as the
1 as the
Use case: Remove username from the array when the user logs off.
usersOnline array is just
['Harry', 'Steve', 'Tom'].
Remove From End of Array
Pop removes the last item in the array.
Use Case: When you are doing Last In First Out (LIFO), pop will get the last item you added to the array out for you.
Bonus: Check Array’s Length
Returns the count of items in the array. The count starts with 1.
Use Case: When you need to capitalize the first letter of each word in the array.
Those are my most used
level 1 array methods.
I hope this article was quick, easy to follow, and helped you learn. Let me know if I need to expand on something or explain it better (in the comments section below).
Next up… Level 2 Array Methods.