In an Array, you have direct access to indices. When an Array is created, memory is simply allocated. However, Arrays don't support direct insertion; to insert, you need to manually write loops to shift elements and then place the new value (or shift and overwrite for deletion). Array operations have constant time complexity, O(1).
In contrast, when using a Linked List, memory isn't pre-allocated. A new node is created for each insertion. However, to retrieve an element from a Linked List, you must traverse it through a linear search.
If you need to scan or access elements randomly, Arrays are more efficient. But if you only need to push or pop from either the head or tail, a Linked List is a better choice.
Can we have an array access with the ability to grow?
Execute the following command in the terminal: npx ts-node src/utils/array-test.ts
, and review the output. You'll observe the following time complexities:
- get => O(1)
- push/pop => O(1)
- un/shift => O(N)
Thus, we can conclude that JavaScript arrays are implemented similarly to ArrayLists!