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.
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.
Bracket notation :
return arr; //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():
- Adds new items to the end of the array push():
- Removes the last item of the array pop():
- Removes the first item of the array shift():
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
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'.