The Complete Guide to Using Arrays in JavaScript


Arrays in JavaScript are variables that can hold more than one value. Traditionally, a variable can hold only one value/element, but with arrays, you can have multiple values/elements stored within one variable itself. This guide will teach you everything you need to know to get started using arrays in your JavaScript code.

Before we get started, if you are looking to learn more about JavaScript or other topics, you should really check out SkillShare, you should really check out SkillShare. Skillshare is an online learning platform with courses on pretty much anything you want to learn. To learn more about Skillshare and its vast library of courses and get 30% off, click the link below:

SkillShare – Online Learning Platform

Now, let’s get started with the tutorial!

Single Element Arrays in JavaScript

As referenced earlier, variables typically hold one value. Listed below are a couple of examples of single value variables:

Example Of JavaScript Variable With A Single Value

let fruit1 = ‘apple’;
let num = 23;
let name= ‘Willy Wonka’;
basic variables with single value in JavaScript
basic variables with a single value in JavaScript

The above examples are two strings (apple and Willy Wonka) and a number (23).

Now, let’s create a couple of single-element arrays. Open up your JavaScript editor or IDE and type in the commands shown below:

const fruits = [‘apple’ , ‘orange’ , ‘banana’];
simple array of fruits in JavaScript
simple array of fruits in JavaScript

Arrays are usually used when a particular category or variable will have a high number of different values.

Sample JavaScript Array holding the names of students
Sample JavaScript Array holding the names of students

For instance, if you’re using the variable/category to store students’ names in a class. Instead of using one variable for each student, you’d instead use one array variable to store the names of all the students.

a JavaScript array holding different value types
a JavaScript array holding different value types

Arrays can also hold different value types. An array can contain strings, numbers, other arrays, boolean values (true, false), and even objects. This may sound really complicated but as you work with arrays, it will become clearer to you how they work.

How to Create an Array in JavaScript

You can create JavaScript arrays in two ways:

  1. Using the Array Constructor.
  2. Using Array Literal Notation.

Using an Array Constructor in JavaScript

Array constructors allow you to create array variables (variables that hold an array). You can either just create your array with no size or values and assign the size/values later or initialize the array with values when you create it. The steps to using an array constructor are listed below:

  1. Declare an array with the variable name and the array constructor.
  2. Initialize it with either the number of values the array will hold or the specific values themselves.

Declaring an Array in JavaScript

In this step, you essentially declare in the code that there is a new array a variable name. However, this does not yet allocate memory to the array. Instead, it only creates the variable of type array.

Declaring an array in JavaScript
Declaring an array in JavaScript

As shown in the screenshot above, you define the variable (in our example, scores) as a new array. The array listed above is not initialized yet. Let’s talk about array initialization next.

Initializing an Array in JavaScript

As referenced earlier, when you initialize an array in JavaScript you either explicitly give the length of the array or the values it will hold. Only then is the array created, and memory is allocated to the said array.

Example of Initializing an Array in JavaScript:

The // you see in the example below indicates a comment. Comments are there to provide additional information and are not part of the array initialization.

let scores = new Array(5); // Initialization
Constructing and Initializing a new Array variable with a length of 5 elements
Constructing and Initializing a new Array variable with a length of 5 elements

In the example shown above, you can see that we are:

  1. Creating a new variable (scores)
  2. Setting it as an Array
  3. Setting the size of the array to 5 elements

What this means is that you have initialized the variable (scores) to hold five elements. As we mentioned earlier, these elements can be a mix of numbers, boolean values (true/false), stings, arrays and even objects.

Array Literal Notation Method in JavaScript

The steps in this method are similar, except the Array constructor isn’t used here. However, you can also create an array while declaring and initializing an array in the same line of code.

Example: Declaration & Initialization In Different Lines in JavaScript

let scores = []; // creates a variable 'scores' that holds an empty array
scores[0] = 25;  // assigns the number 25 to the first element of the array
scores[1] = 35; // assigns the number 35 to position 1 (2nd element) of the array
scores[2] = 'array'; // assigns the string 'array' to position 2 (3rd element)
scores[3] = true; // assigns the boolean value true to position 3
Creating and initializing an array that holds four elements in JavaScript
Creating and initializing an array that holds four elements in JavaScript

In the example above, we declared our variable (scores) as an empty array ([]). We use the open ([) and closed (]) braces with no space in between to indicate an empty array. We then initialize each element in the array with values.

Assigning the number 25 to the first element in a JavaScript array
Assigning the number 25 to the first element in a JavaScript array

In order to add a value to a specific array element, you need to reference the array index in your initialization. In the example above, we want to add the number 25 to the first element in the array. Array elements start at position 0, not 1.

So you would write:

scores[0] = 25; // array index (position) goes between opening and closing brace
JavaScript array index 0
JavaScript array index 0

The element position you want in the array, known as the array index of the element, is written between the opening and closing braces (in our example [0]).

If you want to output your array to your screen, you can use the console.log method and pass in the variable. For our example, you would type the following:

console.log(scores);

This outputs the contents of the variable scores to the console, which you can see in the screenshot below:

Outputting the contents of a JavaScript array
Outputting the contents of a JavaScript array

As you can see, all the elements of our array (scores) are outputted to the console in order.

You can also declare and initialize an array in JavaScript using literal notation as shown in the example below.

Example: Declaration & Initialization a JavaScript Array on Same Line

let scores = [25, 35, 'array', true]; // Declaration + Initialization
declaring and initializing an array in JavaScript in one line
declaring and initializing an array in JavaScript in one line

How to Add an Element to End of Array in JavaScript

JavaScript provides several methods that allow you to add or remove elements at the beginning or end of the array. The first method we will discuss is the push method. The push method appends or adds an element to the end of the array.

Using our scores array we set up earlier, we can use the push() method to add a value (a string in our example) to the end of the scores array as shown in the code snippet below:

let scores = [25, 35, 'array', true];
scores.push('chocolate');
Appending a string to a JavaScript Array using the push() method
Appending a string to a JavaScript Array using the push() method

As you can see from the code editor screenshot above, when we use the push method and then output the contents for the scores array, our new string (chocolate) has been appended to the end of our scores array.

Next, we will cover how to add a new element to the beginning of the array using the unshift method.

How to Add an Element at the Beginning of an Array in JavaScript

The unshift() method prepends or adds an element to the front of an array. Enclosed below is an example of how to use the unshift() method to add the boolean value false to the beginning of an array (scores):

scores.unshift(false);
Adding an element to beginning of a JavaScript array using the unshift() method
Adding an element to the beginning of a JavaScript array using the unshift() method

When we output our array after using the unshift() method, you can see that our boolean value, false, has been added to the beginning of our array scores.

But what if we want to remove elements from the beginning or end of our array? Fortunately, JavaScript provides two methods, pop() and shift(), that allow us to do so.

How to Remove an Element from the End of an Array in JavaScript

To remove an element from the end of an array in JavaScript, we use the pop() method. Enclosed below is an example of how to use the pop() method:

scores.pop();

Notice anything different from our earlier methods? With the pop method, we don’t have to pass in a value. That is because the method already knows it has to remove the last element of the array so there is no need to pass anything into the method.

Removing the last element in a JavaScript array using the pop() method
Removing the last element in a JavaScript array using the pop() method

As you can see in the screenshot above, after using the pop() method, the last element of our scores array (chocolate) has been removed from the array.

Next, we will cover how to remove the first element of an array using the shift() method.

How to Remove an Element from the Beginning of an Array in JavaScript

Removing an element from the beginning of an array is very straightforward using the shift() method. Enclosed below is an example of how to use the shift() method to remove an element from the beginning of an array:

scores.shift();
Removing the first element from a JavaScript array using the shift() method
Removing the first element from a JavaScript array using the shift() method

The shift() method removes the first element from an array as shown in the screenshot above.

Next, we will cover how to remove specific elements in an array using the delete() and splice() methods.

How to Remove an Element from an Array in JavaScript

There are two ways by which you can delete elements from an array.

  1. Using the delete operator
  2. Using the splice method

Using the Delete Operator to Remove an Element from a JavaScript Array

The delete operator removes the current value from a JavaScript array using the index of the element. The index is the position of the element in the array.

let scores = [false, 25, 35, 'array', true, 'chocolate'];
delete scores[3];

So, in the example above, if I wanted to remove the string ‘array’ from the scores array, I would use the delete operator on the scores array and pass in the string ‘array’ index.

Removing the value in a JavaScript array using the Delete operator
Removing the value in a JavaScript array using the Delete operator

Notice in the output that the array is still the same length? That is because while the delete operator removes the value in the array element, it does not remove the element position. The result is that you have an undefined element at the index you used the delete operator on (in our case, position 3 of the scores array).

You may be asking yourself, this works great but what if I have a huge array and I don’t know offhand the index of the value I want to remove using the delete operator? JavaScript has you covered here with the indexOf method. You can use the indexOf method to get the index of a value you pass into it. Sounds confusing? Well, let’s show an example:

let scores = [false, 25, 35, 'array', true, 'chocolate'];

delete scores[scores.indexOf('array')];

In the example above, I created the scores array in the first line. I then used the delete operator on the scores array but this time, inside the braces, I used the indexOf method on the scores array, passing in the string ‘array’. If you are just getting started, this can be confusing, but it will become more natural as you use it more and more.

Removing the value in a JavaScript array using the Delete operator and the IndexOf method
Removing the value in a JavaScript array using the Delete operator and the IndexOf method

As you can see, using the indexOf method allows us to remove the value we want without having to know the actual position of that value. Pretty cool, right?

But what if I want to remove the value and the element from the array? Then we need to use the splice() method, which we will cover next.

Removing Elements from a JavaScript Array using the Splice() method

The splice() method is a little different from the other methods we have used as it takes two arguments:

  • start position (first element to be removed)
  • how many elements after that should be removed

An example of using the splice() method would be:

scores.splice(2, 1);
Removing a single element from a JavaScript array using the splice() method
Removing a single element from a JavaScript array using the splice() method

The example above removes one element from the array, which is the element at position 2 of the array. As you can see, 35 was the value at position 2 of the scores array. Once we ran the splice method, however, you can see from the output 35 is no longer in the array. Additionally, you should notice that the size (or length) of the array has changed as both the value and the element are removed.

How to Remove Multiple Elements from an Array in JavaScript

Let’s use an example of how to remove multiple elements from an array.

let scores = [false, 25, 35, 'array', true, 'chocolate'];

scores.splice(1, 3);

Let’s say we want to remove elements at positions 1, 2, and 3 (25, 35, and ‘array’) from the scores array. The code snippet above removes three elements starting at position 1 of the array.

Removing three elements from a JavaScript array using the splice() method
Removing three elements from a JavaScript array using the splice() method

As you can see from the output of the splice() method shown in the screenshot above, the elements that were at positions 1-3 of the scores array (25, 35, ‘array’) have been removed from the array.

How to Clear an Array in JavaScript

You can clear an array by simply assigning the array variable an empty array. Check out the example code below:

let scores = [false, 25, 35, 'array', true, 'chocolate'];
scores = [];
Clearing a JavaScript array
Clearing a JavaScript array

As you can see in the output above, once we set the scores array to an empty array using the [] braces, the array became an empty array.

How to Loop Through an Array in JavaScript

Sometimes, you want to print out or read in each element of an array one at a time. In order to do this, you need to loop through the array. While you can do this using traditional looping mechanisms, JavaScript has a built-in array loop.

So let’s say we want to loop through each element of our scores arrays and output the element to the console, we would use the following code to do so:

let scores = [false, 25, 35, 'array', true, 'chocolate'];

scores.forEach(element => {
    console.log(element);
});

The code may look a little strange but it actually is very descriptive of what it is doing. You are running the forEach() method on the scores array. Inside the curly braces {} you are outputting the element to the console.

Looping through a JavaScript array and outputting each value to the console
Looping through a JavaScript array and outputting each value to the console

As you can see, the forEach method iterates over the scores array and outputs each value of the array to the console.

Popular JavaScript Array Methods

MethodHow To Write In JavaScriptDescription
concat()string.concat(string1, string2, …, stringX)This concatenates or joins two or more strings together.
reverse()array.reverse()This reverses the positions of the elements in an array.
slice()array.slice(start, end)This returns elements from an existing array as a new array.
forEach()array.forEach(function(currentValue, index, arr), thisValue)This executes an operation or a function for each element in the array.
includes()array.includes(element, startIndex);This method checks if a value is there in an array or not. It then returns true or false.
Key JavaScript Array Methods You Must Know

Want More Tips and Tricks? Subscribe to our Newsletter!

If you haven’t already subscribed, please subscribe to The Productive Engineer newsletter. It is filled with tips and tricks on how to get the most out of the productivity apps you use every day. We hate spam as much as you do and promise only to send you stuff we think will help you get things done.

Newsletter

Subscribe to our newsletter and stay updated.

Check Out Our YouTube Channel!

How to Use the Outline Tool in Google Docs

We have a YouTube channel now and we are working hard to fill it with tips, tricks, how-tos, and tutorials. Click the link below to check it out!

link to our YouTube page

Do you use the same password for multiple sites? Do you have trouble remembering all your passwords? You should try 1Password! 1Password is secure and allows you to log in to sites and fill forms securely with a single click. I use 1Password for all my passwords and it really makes managing all my passwords simple.

For more information on 1Password and to get a 30-day free trial, go to 1Password at the link below:

1Password – The world’s most-loved password manager

Check out our Resources Page

Check out our resources page for the products and services we use every day to get things done or make our lives a little easier at the link below:

Link to the resources page

Looking to Get Started Blogging or on YouTube?

Getting started can seem daunting and scary (I know it was for me) but it doesn’t have to be. I was very lucky to find a program that that has helped me grow my blog to over 35,000 page views and a YouTube channel that is growing month-over-month.

Project 24 by Income School is the program that I have used. I have been a member for over a year now and just renewed my membership. I cannot recommend Project 24 enough! For more information on Income School, click the link below:

Project 24 byIncome School – Teaching You How to Create Passive Income from Blogs and YouTube

Recent Posts

Complete Guide to JavaScript Arrays