Javascript Array
Overview
JavaScript Arrays represent the collection of elements (or items) stored under a single variable.
This simply means that when we want to store multiple items in a single variable, we can use Arrays in JavaScript. Arrays in JavaScript can store the items belonging to any data type. In addition to this, there are many methods of Arrays in JavaScript that make it easy to work with JavaScript Arrays.
Let us dive deep into the world of Arrays in JavaScript.
Introduction to JavaScript Arrays
Before understanding arrays, let us see the need of arrays. Suppose I have four employees whose salaries are:
Output:
Now to double the salary of each employee I have to explicitly multiply each of them with 2:
Output:
We wrote the code of each element individually, which is quite boring as well as generates unnecessary code. What if we have one thousand employees? It would be a lot of code and a hectic task as we have to declare each variable separately, then store a value in it and repeat the process. Hence we needed something that could solve this problem without writing code for each element individually. This is where the JavaScript Arrays come into the picture.
JavaScript Arrays are the objects that can store multiple items(or values) irrespective of their data types under a single variable. In fact, Arrays don't just provide a way to store multiple values, they also provide a way to access them randomly in constant time(that is time complexity).
In many programming languages, we can store multiple items in arrays, but they must be of the same data type like we can not store a number value inside an array having string values, But in JavaScript, we have the freedom of storing any data type value in an array be it number, string, null, undefined, float, or even an array can be stored inside an array.
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.
Declaring JavaScript Array
Now let us see how we can declare JavaScript Arrays. There are two ways of declaring a JavaScript Array.
Using the JavaScript Array Literal
The Array literal way allows us to add the elements separated by a comma and enclosed inside square brackets. This is the easy as well as the preferred way of declaring JavaScript Arrays.
For example:
Output:
Using the JavaScript new Keyword (array constructor)
As mentioned above, the arrays are objects in JavaScript; hence they can be created using the new keyword also.
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.
For Example,
The output is the same for both of the ways.
Output:
Common Operations of JavaScript Array
JavaScript provides several operations to work with arrays. Let us discuss them one by one.
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:
output:
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.
Syntax: arrayName[index]
For example,
Output:
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[2].
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
For Example,
Output:
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
If we want to access all the elements of the JavaScript Array, then we can use for( or for-each) loop.
For example, In the below-given example, we want to get the square of each element of the array, in such situations, we can use the loops(here for loop) in JavaScript.
Output:
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
If we want to add an element(or more) to the end of a JavaScript Array, we can use an array method called push(). The push() method as the name suggests, pushes the specified element(or elements) to the end of an array.
Example:
Output:
Example 2:
Output:
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
If we want remove an element from the end of JavaScript Array, we can use an array method called as pop(). The pop() method as the name suggests pops an element from the end of an array. For example,
Output:
In the above-given example, 'bus' is popped from the array vehicles.
Remove an Item from the Beginning of an Array
If we want to remove an element from the beginning of JavaScript Array, we can use an array method called shift(). The shift() method as the name suggests, shifts the array elements to the left by removing an element from the beginning of the array. For example,
Output:
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
If we want to add an element(or elements) at the beginning of JavaScript Array, we can use an array method called unshift(). The unshift() method as shifts the previously stored elements to the right and inserts the new specified element(s) at the first index position of the array. For example,
Example:
Output:
Example:
Output:
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
If we want to find the index of any element in the JavaScript Array, we can use an array method called indexOf(). The indexOf() method, as the name suggests, returns the index of the specified element from the array. If the specified element is not present in the array, the indexOf() method returns -1. For example,
Example:
Output:
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.
Example:
Output:
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
If we want to remove an element from the JavaScript Array, we can use an array method called splice(). The splice() method can be used to remove, add or even replace an element(s) in the array. It should be noted that the modifications done using the splice() method affect (or change) the original array.
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.
Example:
Output:
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
If we want to delete the specific number of items(or elements) from the JavaScript Array using the index position then also we can use the splice() method as I have already mentioned in the above-given heading. Let us see an example of the same. Example 1:
Output:
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.
Example:
Output:
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
If we want to add an element(or elements) in the JavaScript Array using the index position, then also we can use the splice() method. Let us see an example of the same.
Example:
Output:
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
If we want to replace an item from the JavaScript Array with another item, then also we can use the splice() method. Let us see an example.
Example:
Output:
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
What if we need to copy the whole JavaScript Array into another variable or the specific content of an array into a variable? In this scenario, we can use the slice() array method. The slice method slices the specified part of the array without modifying the original array. Hence this method proves very helpful in copying down a certain part or the whole array into another variable.
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.
Example:
Output:
Explanation:
- 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?
JavaScript Arrays are also objects. We can verify this using the typeof operator. As the name suggests, the typeof operator returns the type of the entity. Let us understand this with an example:
Output:
We can see that the typeof operator gives object for arrays as well as objects. Hence it can be said that Arrays are also Objects in JavaScript. There's also a similarity between arrays and objects. The objects in JavaScript have named values which means that the values are stored in the form of "key
Array Properties
There are three properties of JavaScript Arrays but the length property is the most used one. So we will discuss only the length property in detail.
- 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
If we want to find the number of elements(or items) present in the JavaScript Array that is the length of an array, we can use the length property of the array. This property returns the length of the array in number format.
Output:
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:
Output:
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.
Associative Arrays
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.
But in JavaScript, Arrays are numbered indexed which means that we can pass a numeral index value to access the array element, but we can not pass a named key to access that element. To be specific, In JavaScript, we have no such thing called Associative Arrays but we have Objects in JavaScript that work the same as the Associative arrays except for the fact that here they are not arrays but the objects.
How to Recognize an Array?
How can we recognize JavaScript Array? Using typeof operator? Not at all. I have already mentioned above that the typeof operator returns object for array because arrays are objects in JavaScript. For example,
Output:
As we are not able to recognize an array using the typeof operator, we will try using other available options like instanceof and isArray() method in JavaScript.
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.
In the above-given example, we have tested if the variable arr is an array or not using the isArray() method. When we passed arr inside the isArray() method and the console logged it,true got printed in the console. But when we passed an object obj in the isArray() method and the console logged it, false got printed in the console. Hence it proves that we can recognize any array using the isArray() method in JavaScript. If the passed value is an array, then true will be returned otherwise, false is returned.
The Difference Between Arrays and Objects
Now we are going to see some main differences between JavaScript Arrays and Object. We have divided the differences into three points that are Use, Modification, and Iteration. Let us discuss each of these in detail.
Use:
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.
Modification:
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.
Iteration:
If we want to iterate over the array elements, we can use different loops available in JavaScript like for loop, for in loop, while loop, for each loop, etc. But one of the most used loops for arrays is the standard for loop. Similarly, we can iterate over object properties using these loops but one of the most used loops for objects is the for of loop.
JavaScript Array Methods
In the below-given table, we have mentioned the method name, its description, and the value it returns. This table can be very helpful when you want to do a quick revision of some of the most used JavaScript Array methods.
Method | Description | Returns |
---|---|---|
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 |
Conclusion
- JavaScript arrays are used to store multiple values inside a single variable.
- JavaScript arrays can be declared using the literal way as well as using the new keyword.
- JavaScript arrays follow zero-based indexing.
- The power of JavaScript arrays can be utilized by using the array methods and properties.
- 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.
- The typeof operator returns the object for arrays as arrays are also objects in JavaScript.
- The instanceof operator and the isArray() method can be used to recognize a JavaScript Array.