This article will describe the ArrayList in JavaScript.
Is There an ArrayList in JavaScript?
In JavaScript, there is no pre-built data type called “ArrayList”. However, JavaScript does have an “array” data type, which allows you to store a collection of values in a single variable. More specifically, arrays in JavaScript are dynamic, which means that you can add or remove elements from the array at any time.
Let’s see an example of using an array as an ArrayList by dynamically adding and deleting elements.
Example 1: Add Elements in ArrayList
Create an array named “ArrayList” that stores numbers and strings:
Now, add a boolean value “true” in an array using the array’s predefined method “push()”:
Add one more element like “23” in an array:
Print the array on the console:
The output indicates that the elements have been successfully added to an array:
Now, let’s delete some elements from an array like an ArrayList.
Example 2: Delete Last Element From an ArrayList
For removing the last element from an array, use the “pop()” method:
Here, you can see that the last element of an array that is “23” has been successfully removed:
Example 3: Delete First Element From an ArrayList
If you want to remove/delete the first element from an array, use the “shift()” method:
Output
Example 4: Replace Element From an ArrayList
Sometimes, we want to replace any element with another element or add an element at any specified index in an array. So, utilize the “splice()” method in that situation. Here, we will add an element at the index 1 and without deleting any element:
It can be seen that the “Linuxhint” is added at the 1st index of an array:
We have compiled all the necessary information relevant to the ArrayList in JavaScript.
Conclusion
In JavaScript, there is no built-in data type called “ArrayList” like in some other programming languages. To create a dynamic list or an “ArrayList” in JavaScript, use an “array” and the built-in array methods to add and remove elements as needed. This article described the arrayList in JavaScript.