What Are JavaScript Arrays, and How To Use Them?

This tutorial demonstrates JavaScript arrays such as creating, manipulating, getting indexes, adding items, removing items, and sorting arrays.

In the world of web development, JavaScript or JS is the essential browser scripting language, and it is responsible for improving users’ interaction with a website. Using the JavaScript programming language, you can make a website more robust, lively, and interactive.

There are many modules of JS. But today, we are going to learn JS arrays. Arrays are one of the crucial tools of JavaScript, which is widely used in web development and programming.

What Is an Array in JavaScript?

In the JavaScript programming language, a collection of data items or objects is called an array, and it stores data as item lists and returns them when required.

In JS, a pair of square brackets [ ] holds the array elements. A comma separates these elements (,). The JS array is different from other programming languages. Because in this array, you can place any type of data that can be a String, Boolean, Numeric, or an Object.

For example, the following code contains three elements of different data types.

var mixedTypedArray = ['Mike', 90 , false];

Do you know?JS arrays do not have fixed lengths, and you can change their size anytime by adding a new value.

How To Create JavaScript Arrays?

There are multiple ways to create JS arrays, and the easiest way is to assign an array value to a variable.

var cars = [ 'honda', 'audie', 'ferrari' ];

The other method is to use the Array constructor with the new keyword.

var cites = new Array('London', 'Sydney', 'Tokyo' );

Remember, the rules for the Array constructor are different. For instance, if you write “new Array(3),” an empty array of three elements will be created.

var items = new Array(3);
document.write(JSON.stringify(items));

Output

[null,null,null]

Also, if you write “new Array(4,8,9)” then you will get an array of three elements with 4, 8, and 9 in it. 

var items = new Array(4,8,9);
document.write(items);

Output

4,8,9

How to Manipulate JavaScript Arrays?

Here, we will dive into the details of array methods to learn how to manipulate JS arrays. Some of the commonly used methods that we will learn about are:

Without further ado, let’s explore the manipulation of JS arrays.

How To Find Indexes and Items in JavaScript Arrays? 

Indexof()

If you wish to know the index of a particular element, you can use this method. It gives the index of the first identical element. So, if an element is repeated, it will not show the result of the other element with a different index value. Moreover, if no result is found, it returns -1. For more clarification, look at the code below.

Syntax

.indexof(searchElement);
.indexof(searchElement, fromIndex)

Example

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
document.write ( names.indexOf( 'BMW' )); // returns 0
document.write ( names.indexOf( 'rob' )); // returns -1 

Includes() 

For inspecting whether an element exists in an array or not, you can use the includes() method. It returns true if the result is found; else, it returns false.

Syntax

.includes(searchElement)
.includes(searchElement, fromIndex)

Example

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
document.write ( cars.includes( 'BMW' )); // returns true
document.write ( cars.includes( 'rob' )); // returns false

How To Add Items to JavaScript Arrays?

Push()

We use the push() method to add a new element in an array. It adds a new element at the end of the array.

Syntax

.push(element0)
.push(element0, element1)
.push(element0, element1, /* ... ,*/ elementN)

Example

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
cars.push('Ferrari');
document.write ( cars );

Output

BMW,Mercedes,Audi,Ferrari

Unshift()

Unlike push(), unshift() adds a new element at the beginning of the array. Just use this method with the array name to add a new value at the start of the array.

Syntax

.unshift(element0)
.unshift(element0, element1)
.unshift(element0, element1, /* ... ,*/ elementN)

Example

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
cars.unshift('Ferrari');
document.write ( cars );

Output

Ferrari,BMW,Mercedes,Audi

How To Remove Items in JavaScript Arrays?

Pop() 

The easiest way to remove array elements is to use pop(). Each time you call this method, it will remove an element from the end of the array.

Syntax

.pop()

Example

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
cars.pop();
document.write ( cars );

Output 

BMW,Mercedes

Shift()

Shift() is another method that is used for removing elements. But we use it to remove elements from the beginning.

Syntax

.shift()

Example

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
cars.shift();
document.write ( cars );

Output

Mercedes,Audi

How To Copy a JavaScript Array?

Slice()

If you want to copy and clone a new array, you can use the slice() method. Remember that it will not affect the original array; instead, it creates a copy.

Syntax

.slice()
.slice(start)
.slice(start, end)

Example

var cars = [ 'BMW', 'Mercedes', 'Audi'];
var carsCopy = cars.slice()
document.write ( carsCopy );

Output

BMW,Mercedes,Audi

How To Add/Remove Multiple JavaScript Array Items?

Splice()

Splice() is used for adding/removing multiple elements from anywhere in the array. But to use it, you must understand its syntax first.

The splice() method can accept three parameters.

  • First is the index where you want to add/remove elements
  • The second is the number of elements you wish to delete. 
  • The third is the new item you want to add.

Syntax

.splice(start)
.splice(start, deleteCountF)
.splice(start, deleteCount, item1)  
.splice(start, deleteCount, item1, item2, itemN) 

Let’s look at a couple of examples to understand this method.

var cars = [ 'BMW', 'Mercedes', 'Audi' ];
cars.splice(0,0,'Honda')
document.write ( cars );

The first parameter tells the splice() to go to index 0. The second parameter shows that we are not deleting any items but adding a new element, ‘Honda’, at index 0. So, the output will look like this. 

Output 

Honda,BMW,Mercedes,Audi

Here’s another example. In the following example, we are deleting the value at the 0 index, and we will not be adding any new value.

var cars = [ 'Honda','BMW', 'Mercedes', 'Audi' ];
cars.splice(0,1)
document.write ( cars );

Output

BMW,Mercedes,Audi 

We can also delete or add multiple values. You can try that code as an assignment and experiment by adding multiple values.

How To Sort JavaScript Arrays?

Sort() 

If you want to sort your arrays alphabetic, ascending, or descending, you can use sort(). But it arranges all elements as strings. So, it will work for you if you have an array of strings, just like you can see in the example below.

Syntax

// Functionless
sort()

// Arrow function
sort((firstElement, secondElement) => { /* ... */ })

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(firstElement, secondElement) { /* ... */ })

Example

var cars = [ 'Honda','BMW', 'Mercedes', 'Audi' ];
cars.sort()
document.write ( cars );

Output

Audi,BMW,Honda,Mercedes

Now let’s see what it will do with the numbers.

var numbers = [ 8,9,12,16,24 ];
numbers.sort()
document.write ( numbers );

Output

12,16,24,8,9

That’s not the correct answer. Is it? To solve this problem, we will need to create a comparator function. And use it inside sort(). Here we will create a function for ascending order.

var numbers = [ 8,9,12,16,24 ];
numbers.sort(function(a, b) {
  return (a-b);
});
document.write ( numbers );

Output

8,9,12,16,24

Quick Facts About JavaScript Arrays 

JS Arrays are different from other languages. Some interesting behavior of JS arrays are:

  • JS arrays can work both as stack and queue. 
  • An array is considered an object in JavaScript.
  • The array elements do not have specific data types. However, they are treated as strings in most cases.
  • Unlike other languages, the length of arrays is not fixed. More elements can be added to JS arrays even after initially defining a length.

Recommended Articles

Other Articles