Arrays are one of the most used Data Structures in JavaScript and pretty much any language. Today I'll be talking about what they are, what they do, and when to use them.

So let’s get to it!

What are Arrays

To start off I'll be talking about Arrays. This is a Data Structure, most programmers are familiar with, that organizes data sequentially as shown below.

let basket = ['πŸ₯§', // 0 index
              '🍀', // 1st index
              'πŸ‡', // 2nd index
              'πŸ’', // 3rd index
              '🍏', // 4th index
              '🍎'] // 5th index

Pretty simple right? Arrays are really nice because they are a small and simple data structure that is contiguous in memory, meaning that each value is stored right next to each other, so you don't have to allocate a lot of space to store data.

Also in JavaScript arrays are resizable and dynamic in nature. In contrast to static arrays in other languages which have a predefined size, so you cannot add more values to them. Instead of static arrays, you need to move the array over to a different location in memory in order to increase the size essentially creating a whole new array.

Methods for Arrays

When using arrays these are some common methods that have varying time complexities:

Note - You do not have to shift the indexes if you are inserting them to the end of the array or deleting the last index.

As we can see there are different types of time complexities for the different types of methods for arrays. But as we notice with the last two, Insertion and Deletion, they differ for the last index of the array. In JavaScript this is also evident from the fact that they have two very special names for their methods:

basket.push()

basket.pop()

As the name implies pop() will delete an index from the end of the array reducing the size. While push() will add to the end of the array increasing the size. Both of which are constant time.

When to use JavaScript Arrays

So Imagine you have a deck of cards:

A good time to use an array could be if you are creating a card game where you are only getting cards from the end of the deck. This will allow you to utilize the O(1) time complexity of pop() and push() to get cards from the top of the deck. Also In a deck of cards the order in which you put the cards matters so it will also be represented by the indices of the array.

In Conclusion

JavaScript Arrays allow us to store memory that is contiguous, of different data types, and ordered. Although it does have some tradeoffs when it comes to insertion and deletion because of shifting the indexes. It has a fast lookup and changing of an index. It can also be the building block to more complex data structures that we will talk about in the future.


Also published here.