All You Need to Know About JavaScript Arrays

JavaScript is one of the most important scripting languages that is used mainly for improving a user’s interaction with a web page. With this programming language, you can make your website more lively, robust, and interactive. Today, JavaScript is being used widely in game development and mobile application development.

In this article, we will cover a specific data type in JavaScript—arrays. Well dig into:

  1. What are Arrays in JavaScript?
  2. Array Operations
  3. Array Methods
  4. Map, Reduce and Filter 

What Are Arrays in JavaScript? 

Arrays in JavaScript are the data type used to store a list of values. JavaScript array objects can be stored in variables and dealt with in the same way you deal with any other data type. The difference is that we can access each value inside the list individually, and perform various activities, such as looping over it.

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

JavaScript Array Operations

Creation of Arrays

The items in an array are enclosed within square brackets. For this example, we’ll imagine that we are looking at a list of cars. 

let cars = ["bmw", "volvo", "honda"];

The array above is only holding integer values, but arrays are capable of holding multiple values of different data types.

Accessing Array Elements

The notation for accessing the elements inside an array is also square brackets. Every element in the array is assigned with an index. By default, the first index of an array is zero. To retrieve a specified element from an array, a pair of square brackets enclosing the index value is used, i.e., cars[0]. To avoid any confusion, think of the index as the number of items to skip, counting from the start of the array. 

console.log(cars[0]);

console.log(cars[2]);

The code above will display the values “bmw” and “honda” respectively on the console. 

Array Length Property

As the name suggests, the length property retrieves the length of the array. 

let len = cars.length;

console.log(len);

The length of the cars array is stored in the variable len. You can view the output on the console. 

Accessing the Last Array Element

Since cars.length retrieves the length of the array, and since arrays use zero-based indexing, the index of the last element is one minus the length. 

cars_length

let last = cars[cars.length - 1];

console.log(last);

Loop Over the Array Items

You can also loop over an array in case you need to access multiple elements from the array at once. We use the forEach method for this, which calls a function once for each element in an array. 

cars.forEach((item, index, array) => {

        console.log(item, index);

      });

The code above displays the name of the cars and their corresponding indices on the console. 

Array Methods

Now that you know more about creating and accessing arrays, we’ll cover the various array methods. There are several built-in methods to use in arrays, and we will go over a few of the most commonly used ones. 

toString() 

The toString() method returns a string relating to the number. The only parameter it takes is the base index. 

let list_Number = [2,4,6,8,10]

            for(let x=0;x<list_Number.length;x++)

            {   let y = list_Number[x]

                console.log(y.toString(2))

            }

The code above converted every item in the array to its corresponding binary string. The output is shown below: 

elements-console

toString()

Push()

The push method is used to push the elements into an existing array. The push() method mutates the array. 

cars.push("Audi");

console.log(cars);

The new array element “Audi” is pushed at the end of the array. 

elements-console-debugger

push()

Unshift()

This method is used to add elements to the front of the array and increases the index of every element by one.

cars.unshift("Toyota")

console.log(cars);

The updated array will look like this: 

updated-array

unshift()

Pop()

This method is used to pop the last element from the array. 

cars.pop()

console.log(cars);

As per the above logic, the last element “Audi” is deleted from the array. 

audi

pop()

Shift()

This method is the opposite of unshift, and it removes the first element of the array. This method shifts all the elements, reducing the indexes of every element by one.

cars.shift();

console.log(cars);

The code above must return our original array with three elements. 

3-elements

shift()

Slice()

The slice() method cuts the array and returns a shallow copy of a portion of an array into a new array object. It takes in two parameters: begin and end. The array is sliced from the index specified as begin till the end index (end index excluded). The original array will not be modified.

If the end parameter is unspecified, the entire array from the begin index is sliced. 

let cars = ["Toyota", "bmw", "volvo", "honda","Audi"];

let cars2 = cars.slice(1)

console.log(cars2);

The output of the code above is as follows: 

ouput-slice

slice()

Consider this section of code: 

let cars = ["Toyota", "bmw", "volvo", "honda","Audi"];

let cars2 = cars.slice(0,4)

console.log(cars2);

Since the end parameter is excluded, the array element at index four is excluded. The output is shown below: 

parameter-excluded

slice() 

Concat()

The concat() method is used to merge two or more arrays into a single one. 

let cars = ["bmw", "volvo", "honda"];

let bikes = ["yamaha", "suzuki", "royal enfield"];

let vehicles = cars.concat(bikes);

console.log(vehicles);

The array bikes is merged with the array cars to the following output: 

/array-bikes

concat() 

Sort () 

As the name suggests, this method is used to sort the array. By default, it sorts the array in ascending order. 

let list_Number = [3,2,6,1,5,4,8,7];

list_Number.sort();

console.log(list_Number);

The output is as follows: 

sort-java

sort() - JavaScript Arrays

Reverse()

To reverse the order of elements in an array, we use the reverse() method. When reverse is used after the sort() method, you get the values in descending order. 

let list_Number = [3,2,6,1,5,4,8,7];

list_Number.sort();

list_Number.reverse();

console.log(list_Number);

The output is as follows:

reverse

reverse() - JavaScript Arrays

Map, Reduce and Filter

Some of the most powerful JavaScript array methods are map, reduce, and filter. Let’s go over these. 

.map()

The map() method is used to create a new array from an existing one by applying a function to each of the elements of the first array. It does not change the original array. 

let num1 = [2, 3, 4, 5, 6, 7];

            let num2 = num1.map(double);

            function double(value) {

                return value * 2;

            }

             console.log(num2)

Here, the map method ensures that the function double is applied to each element in the array, thus multiplying the elements by two and storing them in the new array num2.

The following is the output:

map-array

map()- JavaScript Array

.filter

The filter() method takes each element from an array and applies a conditional statement against it. If this condition is true, the element gets pushed to the output array. If the condition is false, the element does not get pushed to the output array. 

let num1 = [2, 3, 4, 5, 6, 7];

let num3 = num1.filter(comp);

function comp(value) {

      return value > 4;

 }

console.log(num3)

All array elements greater than four will be pushed on to the output array num3. 

filter-array

  filter() - JavaScript Array

.reduce

The reduce() method reduces an array of values to just one value. The reduce function is run on each element of the array to get the single output value. This method does not reduce the original array.

let num1 = [2, 3, 4, 5, 6, 7];

let num4 = num1.reduce(sum);

function sum(total, value) {

return total + value;

 }

console.log(num4)

The sum of the array is calculated and reduced to a single value., and this value is stored in the output array num4. 

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Next Steps

Although this article provided a basic introduction to JavaScript array, to learn more about JavaScript in its entirety, then a course certificate is highly recommended. Simplilearn's JavaScript Certification Training course helps individuals master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. Students also have the opportunity to apply their skills by building a real-time chat application.

If you have any questions or feedback, let us know in the comments section. Our experts will get back to you immediately. 

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.