Before understanding arrays, let us see the need of arrays. Suppose I have four employees whose salaries are:
Now to double the salary of each employee I have to explicitly multiply each of them with 2:
Every element in the array has an index associated with it. It means that we can access any element directly using its index. We will discuss more on this in subsequent sections.
Note: It is recommended to avoid declaring arrays using the new keyword as much as possible and declare arrays using the array literal because the new keyword way is slower as it calls the array constructor while the array literal way is faster as well as more readable.
Let us see an example using the new keyword in the console.
The output is the same for both of the ways.
Creating an Array
As mentioned above, arrays can be created in two ways but the literal method is the preferred way. So let us create an array using the array literal method:
Access an Array item using the index position
All of the array items are indexed, which means that every element of the array is assigned a particular index based on its position from the very first element of the array, and the first element has the index value of 0(zero). The main purpose of indexing is the ease of access. In simple words, we can easily access the array elements using their indexes to perform various operations on those elements.
In the above-given example, we have 9 array elements in total, suppose we want to access the third element that is "from", then we need to write the array name with the index value 2(as indexing starts from zero, the third element stands at second index value) in the square brackets that is myArray.
Changing an Array Element
To change the value of an array element first, we need to access it using its index and then place an equal operator with the new desired value.
Syntax: arrayName[index] = newValue
In the above-given example, before changing the value, we had a value of at the 2nd index position of the array myArray, then we changed the value of that element from value 3 to value 7 at the index 2. Hence on printing the array, we got in place of .
Loop Over an Array
In the above-given example of array myArray having values ranging from 1 to 5, we iterated the whole array using for loop to access its values and then modified them. We started the iteration variable from 0 because array indexing starts from zero, and we ran the loop till the length of the array. We used the length property of the array to get its length.
Add an Item to the End of an Array
On observing the above-given examples, you will notice that we can either push a single value or multiple values in the specified array using the push() array method, and the pushed values get added inside the array.
Remove an Item from the End of an Array
In the above-given example, 'bus' is popped from the array vehicles.
Remove an Item from the Beginning of an Array
In the above-given example, we have removed the first element car from the array vehicles using the shift() array method.
Add an Item to the Beginning of an Array
In the 1st example, We have added an element van at the beginning of the array vehicles using the unshift() array method. In the second example, we have added multiple elements at the beginning of the array vehicles using the unshift() array method.
Find the Index of an Item in the Array
In the above-given example, we used the indexOf() method to find the index of the element truck in the array vehicles, and it returned 2 as that element was present at the index value 2.
In the above-given example, we used the indexOf() method to find the index of the element van in the array vehicles and it returned -1 as that element was not present in the array.
Remove an Item by the Index Position
The splice() method accepts three arguments, from which two are optional.
- The first argument is the index position from which the specified operation starts.
- The second argument is the number of elements to be removed starting from the index position.
- The third argument is the element(s) that needs to be added to the array.
Let us see an example of removing an element by the given index position.
Here in this example, we have used the splice() method to remove an element from the index 1. The first argument is telling to start the operation from index 1 while the second argument is telling to delete 1 element from that index. Hence the element at index 1 that is 'one' got deleted(or removed) from the array.
Remove Items from an Index Position
In this example, we have removed the array elements starting from index 2 till the last element. As we have not passed the no. of items to be removed, all the elements from index 2 get removed.
In this example, we have removed three array elements starting from index 2 . As we have passed the no. of items to be removed, that is 3, three elements from index 2 got removed if we pass 4, four elements will be removed.
Add item at an Index Position
In this example, the arguments that we passed inside the splice() method are
- 2 is the index from where the operation starts.
- 0 indicates that zero elements will be removed, that is, no removal of elements.
- elements than all the elements(separated by comma,) that need to be inserted.
We passed three new elements; hence three new elements were inserted in the array starting from index 2.
Replace an item at an index position
In the above-given example, we have replaced an element three at the index position 3 with a new element newThree using the splice() method. The passed arguments in the splice() method are:
- 3 is the index from where the operation starts.
- 1 indicates that zero elements will be removed, that is, no removal of elements.
- newThree is the element that needs to be inserted.
Copy an Array
The slice() method accepts at most two arguments that are optional.
- The first argument indicates the index value to the start of the operation(extraction/copying the elements)
- The second argument indicates the index value just before which operation ends.
If we don't pass any argument, then the whole content of the array gets copied(or extracted).
Let us see an example of the same.
- The array floors is the array from which we have copied the elements in other arrays. When we print the array floors We get all the floors (elements) printed in the console.
- On the array allFloors we used the slice() method without any argument; hence the elements of the array floors got copied inside it.
- On the array nFloors we used the slice() method with one argument only; hence all the elements form that passed index value till the last index value got copied in the array nFloors.
- On the array threeFloors, we used the slice() method with two arguments, 0 indicates the index position from where the operation starts, and 3 indicates the end index position.
How Arrays are objects?
- constructor: This property returns the function which created the prototype of the Array Object.
- length: This property can be used to set as well as return the number of elements present inside the array.
- prototype: This property can be used to add methods and properties to the Array object.
Let us now discuss the length property in detail.
The Length Property
The output 8 tells that there is a total of 8 elements present inside the array.
It should be noted that it does not count the elements present inside the inner array of the array. Let me give you an example:
Here in the above-given example, the length of the array is returned as 6 because there are a total of 6 elements present inside the array that is 5 numbers from 1 to 5, and one inner array containing the elements from 6 to 10. The elements of the inner array are not counted for getting the length of the outer array.
First things first, What are Associative Arrays? Associative arrays are also known as maps or dictionaries or hashes. The main speciality of these arrays is that they can contain data in the form of a key: value pair where we can access any value using a named key linked to it.
How to Recognize an Array?
Using instanceof operator
The instanceof operator as the name suggests can be used to check the instance of the value. Let us see the examples for a clear understanding.
In the above-given examples, the first console.log statement prints true as the array arr is the instance of Array. Hence using the instanceof operator, we can recognize an array.
Using isArray() Method
The isArray() method tests if the passed array is an array or not. It returns true if the passed array is an array, otherwise it returns false.
The Difference Between Arrays and Objects
If we want to store all the elements in a single variable and without any key(or name) of the values, we can go with arrays as arrays are the best choice in such a scenario, but if we want to store the elements in the form of key: value pairs, objects can be used effectively.
Objects generally represent a particular entity it can be a car, a student, an employee, a machine, or anything. This object can have different characteristics based on the entity which are called 'properties' of the object. These properties are in the form of key: value. Hence both arrays as well as objects serve a specific purpose and can be utilized for specific use-cases.
Firstly we need to access the array elements or object elements before modifying them. Array elements can be accessed using the index values of those elements, while object elements can be accessed using the name of the values.
For accessing the array elements, we have one notation that is square brackets notation, in which we pass the index value inside the square brackets but for accessing object elements we have two notations available that are dot notation and square brackets notation. After accessing the array or object, they can be modified, and both can have any value of any data type, be it string, number, even array, or any other data type, literally.
|pop()||This method removes the last element of the array||removed element|
|push()||This method inserts a new element to the end of the array||new array length|
|unshift()||This method inserts a new element to the beginning of the array||new array length|
|shift()||This method removes the very first element of the array||removed element|
|slice()||This method copies the whole or specific part of the array||new array|
|splice()||This method can add, remove and even replace elements in array||array having removed elements(if any)|
|includes()||This method checks the presence of specified element in array||boolean value|
|indexOf()||This method search an element in array for its index||index(if element found) else -1|
|concat()||This method concatenate(or combine) two or more arrays||resulted array|
|sort()||This method sorts the array string elements alphabetically||sorted array|
|reverse()||This method sorts the array string elements alphabetically (in descending order)||sorted array|
|find()||This method returns the first element that passes the specified test||first element(which passed the test)|
|findIndex()||This method returns the index of the first array element that passes the specified test||index of the first element(which passed the test)|
|isArray()||This method checks if the passed value is an array or not.||boolean value|
- The push() method pushes the specified element(or elements) to the end of an array
- The pop() method pops an element from the end of an array.
- The shift() method shifts the array elements by removing an element from the beginning of the array.
- The unshift() method unshifts the older elements and inserts the new specified element(s) at the first index position of the array.
- The splice() method can be used to remove, add or even replace an element(s) in the array.
- The length gives the length of the array.
- The typeof operator returns the type of the entity.