Introduction to Data Structures and Algorithms With Modern JavaScript

JavaScript Arrays

As a JavaScript developer, you will use the array often; it is the most commonly used data structure. Arrays in JavaScript come with a lot of built-in methods.

Introducing Arrays

Arrays are one of the most fundamental data structures. If you have ever programmed before, you’ve most likely used an array.

1 var array1 = [1,2,3,4]; For any data structure, developers are interested in the time and space complexity associated with the four fundamental operations: access, insertion, deletion, and search.

Insertion

Insertion means adding a new element inside a data structure. JavaScript implements array insertion with the .push(element) method.

Screenshot 2022-02-21 at 23.38.34.png

The time complexity of this operation is O(1) in theory. It should be noted that, practically, this depends on the JavaScript engine that runs the code. This applies to all natively supported JavaScript objects.

Deletion

JavaScript implements array deletion with the .pop() method. This method removes the last-added element of the array. This also returns the removed element.

Screenshot 2022-02-21 at 23.40.47.png

Another way to remove an element from an array is with the .shift() method. This method will remove the first element and return it.

Screenshot 2022-02-21 at 23.41.51.png

Access

Accessing an array at a specified index only takes O(1) because this process uses that index to get the value directly from the address in memory. It is done by specifying the index (remember that indexing starts at 0).

Screenshot 2022-02-21 at 23.43.26.png