Data Structures 101: a tutorial on arrays in JavaScript

Jul 07, 2020 - 14 min read
Debbie Otuagomah
editor-page-cover

Data structures are an important part of programming and coding interviews.

These skills demonstrate your ability to solve ambiguous problems, think complexly, and identify patterns in code. Data structures are useful for organizing data. Your programs will be better if the include cleaner, more efficient data structures.

Arrays are an important data structure for any software developer. This way of organizing data allows us to store elements using indexes or keys.

Today, we will take a deep dive into arrays. By the end, you’ll know how to create and use arrays in various programming languages.

We will cover:

What are arrays?

A data structure is a way to organize data in a computer, so it can be effectively used in a program. An array is a type of data structure you can use to store some data you want to use in your program.

Arrays are a collection of individual values separated by a comma each with its own index/location. This collection could be anything: numbers, objects, more arrays, etc. In an array, the values, called elements, are stored in contiguous memory locations.

This means that all the elements are all in a sequence and they share a common border. The number of elements store in an array is referred to as the array’s length.

An array is one of the most efficient ways to store and access a sequence of values or store a collection of data with similar elements. Arrays help to store data that would be otherwise cumbersome to put away.

Imagine you have a clothing store and you need to take stock of the number of items sold on ten different days. Let’s also assume that you need to access and store the mean and median of these values. Without arrays, you would have to create many different variables that would take up a ton of space and consume time.

This could make your code really messy as the number of days increases. Instead, we can use arrays to store and manipulate that data!


Basic structure of arrays

The index of an element in an array is used to identify its location. For instance, if our array contains five numbers: 67, 12, 90, 76, 19, 38, 7. The index of 67 is 0, and that is its location in the array.

The index of 12 (the second element) is 1, and so on. Indexes always start from zero and increase by one. Let’s look at a visual example.

The image above shows an array of the elements A, B, C, and D, and their corresponding indexes. The array length would be four since there are four elements. The numbers beneath the elements refer to the places that the letters exist in the computer’s memory. Now, let’s look at an example of a small array of numbers using JavaScript code.

Here, you can see our elements between the brackets []. Quiz yourself: what would the indexes of each element be?

var numbers = [67, 12, 90, 76, 19, 28, 7];

Advantages and disadvantages of arrays

Every data structure has its advantages and disadvantages due to its basic organization.

Some data structures are better for certain uses than others, so it’s important to know what arrays do well and what they are not best suited to perform.

Pros

  • Store similar data of the same type.
  • Store data when you already know the number of all the elements
  • Implement other data structures like trees, linked lists, graphs, stacks, etc.
  • Store elements in different dimensions of arrays: two-dimensional or multidimensional.
  • An array allocates memory in contiguous memory locations for every element. This avoids memory overflow.
  • Iteration in arrays runs faster compared to other data structures.
  • An array, once declared, can be reused multiple times. This improves code readability.

Cons

  • If you want to use an array, you have to know the number of elements you want to store beforehand. It is impossible to add new/extra values once you declare it.
  • The memory that is allocated to an array at declaration cannot be increased or decreased.
  • Allocating more memory than you need can waste memory space.
  • The cost of deleting and inserting elements is high because the elements of an array are stored in contiguous memory locations.
  • Errors show up at runtime instead of compile-time because an array does not verify the indexes when compiling.

Uses of arrays

Now we know what arrays look like and their advantages, but what can you actually do with an array? Let’s take a look. An array can:

  • Copy and clone elements
  • Insert and delete elements
  • Search and sort elements

Arrays allow you to maintain multiple variable names and large data with a single name. This removes the confusion of using multiple variables and improves code readability. You can also perform different matrix operations with the use of two-dimensional and multidimensional arrays.

Arrays can be used for sorting data elements. Different sorting techniques like bubble sort, insertion sort, and selection sort use arrays to store and sort elements easily.

An array can also be used for CPU scheduling. It allows one process in your program to use the CPU while the execution of another process is on hold.


Get started with arrays

Writing or declaring an array differs from language to language, but one thing all these different variations have in common is that the array always holds a collection of data. In this section, we will look at how to declare an array in JavaScript, Java, C++, and Python.

In each example, we will use the test scores of a high school student as a use case. Let’s say our student Tonia scored 78, 90, 62, 88, 93, and 50 in six subjects respectively.

To use an array in a program, you must declare a variable to reference the array, and then, create the elements of that array.

Now, let’s build this array in different languages!


Declaring an array in JavaScript

In JavaScript, the syntax to create an array is:

var array_name = [item1, item2, ...];

If we want to create an array that holds Tonia’s test scores, we can name our array, test_scores and put all the elements inside the square brackets like so:

var test_scores = [78, 90, 62, 88, 93, 50];
console.log(my_array)

Declaring an array in Java

In Java, the syntax is a little different. First, you have to declare the variable type and then insert the values you want to store with an array literal. If we wanted to create an array of Tonia’s subjects, it would look like this:

String[] subjects;

String[] subjects = {"Create writing",
                     "Marketing",
                     "Japanese",
                     "Calculus",
                     "Computer science",
                     "Physics"},

An array of integers, the corresponding scores for these subjects, would look like this:

int[] testScores = {78, 90, 62, 88, 93, 50};

Declaring an array in C++

Arrays in C++ are more similar to Java than JavaScript. In C++, you can create an array by creating the array variable and initializing the elements like so:

int testScores[] = {78, 90, 62, 88, 93, 50};

Here, the compiler will create an array of size 6, that houses all of Tonia’s scores.


Declaring an array in Python

Python does not have built-in support for arrays, so we use lists to create them instead. First, we create the array variable name then, we initialize all the elements we need like this:

test_scores = [78, 90, 62, 88, 93, 50]

Using array literal and array constructor

It’s important to note that there is another common way to create an array in popular languages. You can either use an array literal, as we showed above with an array declaration in JavaScript, but we can an array constructor.

The Array() constructor is used to create Array objects. A constructor is a function that creates an instance of a class called an object. With an array constructor, we can have multiple parameters.

To use an array constructor, you declare the array with the help of a built-in class and initialize your elements by passing them into the brackets.

In JavaScript, it looks like this:

var testScores = new Array(78, 90, 62, 88, 93, 50);
console.log(testScores);

No matter the way you declare an array using the methods above, it works. If you console.log both pieces of code separately, you will get the same array.

To learn more about constructors in JavaScript, check out our EdPresso shot What is a constructor in JavaScript?


Keep the learning going.

Learn data structures for JavaScript coding interviews without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments - making learning quick and efficient.

Data Structures for Coding Interviews in JavaScript



Using and modifying an array

Now that we know how to create an array, we need to learn how to apply operations and functions to make them useful for our program. We have the stored data, but what do we do next?

Well, let’s take a look at some of the common uses and modifications to arrays that are applied to most computer programs.


Accessing a value in an array

If you want to access an array, you first need to know the location of that array. This is why knowing how indexes work is important.

For instance, if we need to access Tonia’s score for Computer Science (93, the highest score) and store it in a variable highestScore, we first need to know its location. If we count from the left, starting at zero, the index of 93 will be 4. Our code for this would look like this:

var testScores = [78, 90, 62, 88, 93, 50];
var highestScore = testScores[4]
console.log(highestScore);

We console.log the highestScore and indeed get 93, which is at index 4. Accessing elements in arrays comes down to knowing the index.


Modify an array

So, what if we wanted to change the value of a score? Let’s assume that the last score was miscalculated, and Tonia actually got a score of 71.

To modify the last element, we find the index of the element we want to modify and set it equal to the new value we want to exchange it with.

In JavaScript, this would look like this:

var testScores = [78, 90, 62, 88, 93, 50];
console.log(testScores[5]);
testScores[5] = 71;
console.log(testScores[5]);

Here, we found that the index of the element we need to change is 5. We console that to be sure and then set it to be equivalent to the new value. Now, if you console.log the last line, you will get the correct test score 71.


Inserting and deleting values

Say Tonia took an extra Accounting class, and we wanted to add that score to the testScores array. To insert an element, there are a couple of methods you can use.

If you want to add a new element to the end of your array, you can use the push() method. Let’s add the score for her Accounting class at the end of the array.

You can do it in JavaScript like so:

var testScores = [78, 90, 62, 88, 93, 50];
testScores.push(82)
console.log(testScores);

As we can see, this adds the new score to the end of the array and increments the index by 1.

You can also add a new element to the beginning of an array using the unshift() method. Say Tonia has another two classes with scores of 74 and 58, and we want them at the front of our array. Let’s see how we’d do that below.

var testScores = [78, 90, 62, 88, 93, 50];
testScores.unshift(74, 58)
console.log(testScores);

Say we want to add an element in the middle of our aray. To insert a new element anywhere in your array except for the beginning or end, you can use the splice() method. In JavaScript, the syntax is like this:

array.splice(index, howmany, item1 ..., itemX);

Here, the index refers to the location you want to add or remove elements. howmany refers to the number of items you need removed, and it is optional. The last part, item1, ..., itemX, defines the new items to be added to the array. They are also optional.

Deleting elements, on the other hand, has a number of methods you can use. The first one is the pop() method. This method lets you delete the last element in an array. If you wanted to remove the last test score, you can use it like so with JavaScript:

var testScores = [78, 90, 62, 88, 93, 50];
testScores.pop();
console.log(testScores);

This method works by appending pop(); to the array variable. If you console.log this, you’ll notice that the last element is gone. In contrast to the unshift() method, you can use the shift() method to remove the first element of an array.

In our example below, we will remove the first element, 78, from the array of test scores and shift all the remaining elements to a lower index. Here’s how it’s done in JavaScript.

var testScores = [78, 90, 62, 88, 93, 50];
testScores.shift();
console.log(testScores);

Passing arrays to a function

A function is like a command or action that manipulates our data. Say we want to apply commands to Tonia’s score.

If you want to pass an array to a function in your program, you can use the spread operator. This is a new JavaScript feature you can use instead of apply(). The spread operator allows you to access the elements of an iterable object.

Since arrays are a type of object that can be traversed in a sequential fashion, it is a good choice here. If we wanted to write a function that takes Tonia’s scores and apply an action to them, we have to pass the testScores array to the function as a parameter.

Our syntax would look like this:

ourFunction(s1, s2, s3, s4, s5, s6) {
// do something to her scores here
}

let scores = [78, 90, 62, 88, 93, 50];
ourfunction)...scores);

Here we have written a placeholder function that will take Tonia’s six scores and do something with them. We create a new variable (an array) to hold the scores and in the last line, and we pass the array to our function.


Print an array

To print an array in JavaScript, you can use the built-in array.values() function. This prints all the elements in a given array.

If you wanted to print out all the elements in the testScores array we have been working with, it would look like so:

var testScores = [78, 90, 62, 88, 93, 50];
testScores.values();

Now we know how to create an array, modify it, delete values, and apply functions to our data. Well done!


Common interview questions for arrays

Questions about data structures are very common for coding interviews. Since arrays are so popular in computer programs, you will likely encounter coding problems about arrays in any coding interview.

Here are common JavaScript interview questions for arrays that demonstrate your mastery of arrays.

  • Find the length of an array
  • Reverse the array in place
  • Find the smallest and largest numbers
  • Remove all the duplicates of an array in place
  • Find the length of the longest consecutive elements’ sequence
  • Remove the first two elements using array destructuring
  • Write a function that determines if an object is an array
  • Given an array of coins, write a function to compute the number of ways you can make that amount using those coins
  • and more

Wrapping up and resources

Well done! You’ve now completed your Data Structures 101 tour of arrays in JavaScript. You’re well on your way to mastering array. There is still a lot to learn about arrays, so keep reading, practicing, and taking courses to aid your learning. One of the best ways to learn about data structures is through hands-on practice.

By working with real-world coding questions or projects, you’ll quickly learn how arrays work and how they integrate with other data structures.

Educative’s course Data Structures for Coding Interviews in JavaScript is an ideal place to start. This course contains a detailed review of all the common data structures and provides implementation level details in JavaScript.

You’ll become well equipped with all the different data structures they can leverage to write better code!


Keep reading about data structures


WRITTEN BYDebbie Otuagomah

Join a community of 500,000 monthly readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.