During the past week I have been learning on basic data structures on freeCodeCamp. The challenges were on Javascript arrays and objects. In this article I'd like to share in my own words what I have learnt pertaining arrays.
What is an array? An array is a collection of related items.
Example of an array Using the ES6 syntax I will initialize and assign value to an array.
let arr=['faith',21,true,['gaiciumia']];
This array contains different items of different data types. This array is also multi-dimensional as it contains another array within itself.
Check the length of an array
At times we want to know how many items an array has. To do this we use the .length property. In our case arr.length will return 4.
Accessing an array's contents At some point in the program you might need to use a single item from your array. To access an item in an array you use the item's index. also keep in mind that javascript arrays index from 0. We use the bracket notation to access an item at the given index in an array.
Bracket notation : return arr[0]; //returns 'faith'
Change the contents of an array Contents of an array can be changed by either adding an item or removing an item. Note: One cannot reassign values to an array using the assignment operator; special array methods have to be used to change the contents of the array
Special array methods:
- Adds new items to the beginning of the array unshift():
arr.unshift('fun'); //arr=['fun','faith',21,true,['gaiciumia']]
- Adds new items to the end of the array push():
arr.push('father'); //arr=['fun','faith',21,true,['gaiciumia'],'father']
- Removes the last item of the array pop():
arr.pop(); //arr=['fun','faith',21,true,['gaiciumia']]
- Removes the first item of the array shift():
arr.shift(); //arr=['faith',21,true,['gaiciumia']]
PS: To use any of the items removed, assign the method calling to a variable. why? each of the methods removes the specified element then returns it(the removed element). Example: let removed = arr.pop(); return removed; //returns ['gaiciumia']
The splice() method
This method is used to remove then add items to an array. Uses: this method takes up three arguments.(the third argument is optional if no items are being added to the array).
- First Argument: the index to start removing from
- Second Argument: how many items to be removed
- Third Argument: items to replace the removed items
Example: let numbers = [1,2,3,4,5]; numbers.splice(1,2,'II','III'); //numbers=[1,'II','III',4,5]
Explanation: Remove two items at index 1 and replace them with 'II' and 'III'.
Javascript arrays are wide and there is a lot to learn about them. For now I'll leave it at that. In my next article I'll write on copying arrays and array items. Leave a comment in case I missed out on something. Thank you for reading through!