JavaScript Arrays

In this section of the tutorial, we will discuss Arrays in JavaScript and their uses to store multiple values in a single variable and performing different operations on it.

Now, let’s move further to understand the definition of Arrays in JavaScript.

What are Arrays in JavaScript?

In JavaScript, we can store a collection of values using Arrays, where each value is known as an element, and each value has a position that is tagged with a numeric value known as an index.

  • In JavaScript, Arrays are untyped, which means an array element can be of any type, and it also allows the collection of different types of elements in the same array.
  • Array elements can also be classified as a form of an Object in JavaScript.
  • This property of Array allows a user to create complex data structures, such as arrays of objects and arrays of arrays.
  • Arrays in JavaScript are dynamic which means they grow and shrink based on the user requirement.
  • Also, it is not required to declare the size of an Array when it is created or to reallocate it when the size changes.

Now, we will dive deep into the operation of Arrays like their creation,read and write, add and delete.

How to create Arrays in JavaScript?

In JavaScript, there are many ways through which a user can create Arrays in a program. We will discuss them one by one below.

Using Array Literals

It is the most basic way of all for creating an Array. We can create an Array using array literals by simply writing a comma-separated list of array elements enclosed within square brackets. We will take a look at it now.

Example:

  • Here, we can clearly note that values in an array literal can be empty, numeric, and they may also of different types.

Example:

  • Here, we can clearly note that values in an array literal need not necessarily be constants, they may also be arbitrary expressions.

Example:

  • Here, we can clearly note that an array can also contain object literals or other array literals.

Using Spread Operator

In ES6+, we have an operator called Spread Operator, that enables a user to include the elements of one array within an array literal.

Example:

  • Here, we can clearly note that the three dot spread, the array arr1 so that its elements become the elements within the array literal that is being created.
  • The Spread Operator is a useful way by which we can create a shallow copy of an array.

Using Array() Constructor

An array can also be created using Array() Constructor, wherein we can always invoke this constructor in three ways:

Call with no arguments:

var arr1 = new Array();

Call with a single numeric argument for specifying length:

var arr1 = new Array(10);

Call with specifying two or more array elements or a single non-numeric element:

var arr1 = new Array(5, 4, 3, 2, 1, "test, test");

Using Array.of()

In ES6+, a previously flawed constructor function Array.of() that treats one numeric argument as the array length of the array to be created. This can be fixed using a constructor function called Array.of().

Array.of() function creates and returns a new array using the argument values as the array elements, irrespective of how many they are.

Example:

  • Here, Array.of() returns empty array with no arguments.
  • Array.of(10) create arrays with a single numeric argument.
  • Array.of(1,2,3) creates arrays having three elements 1, 2, 3.

Using Array.from()

Array.from() is yet another way of creating arrays in JavaScript. It passes an iterable or array-like object as its first argument and returns a new array having elements of that object.

Example:

  • Here, we can note that Array.from() can also make a copy of an array.

Array.from() can also make a true-array copy of an array-like object. Array-like objects are non-array objects having a numeric length property and having values stored with properties whose names are integers.

Example:

  • Here, we can note that Array.from() is making a true-array copy of an array-like object.
  • Another important thing about Array,from() is that it can also accept an optional second argument.

How to Read/Write Array elements in JavaScript?

In JavaScript, accessing an array for read/write can be done using a [] operator. There should be a reference to the array on the left side of the brackets. An arbitrary expression having a non-negative integer value should be inside the brackets.

We will get the idea of the syntax for both read and write the array element by the example given below.

Example:

  • Here, in line 6, the array arr consists of one element.
  • In line 7, array arr reads element 0.
  • In line 8, array arr writes element 1 with the value 3.14.
  • In line 9, array arr assigns index value to 2.
  • In line 10, array arr writes element 2 with the value 3.
  • In line 11, array arr writes element 3 with the value “CODEDEC”.
  • In line 12, array arr reads element 0 and 2, and writes element 3 with the value of element 0.

All the above-declared syntax are legal JavaScript statements.

One of the special features of arrays in JavaScript is that when a user uses property names that are non-negative integers less than 2^(23)-1, the array automatically maintains the value of the length property.

  • Arrays in JavaScript are special kind of objects.
  • The square brackets used to access the array elements work in the same way like square brackets used to access object properties.
  • JavaScript engine converts the numeric array index specified to a string. It is helpful to clearly distinguish an array index from an object property name.

Example:

  • Here, in line 6, a plain object is created.
  • In line 7, object a is indexed with an integer 1.
  • In line 8, “one” is the numeric and string property names. Both are the same.

What is a Sparse Array in JavaScript?

In JavaScript, when an array does not have contiguous indexes starting at 0, then such array is known as a Sparse Array.

  • In general, the length property of an array determines the number of elements in the array.
  • For an array to be sparse. the length property of the array should greater than the number of elements.
  • Sparse arrays cannot be created using the Array() constructor or by assigning to an array index larger than the current array length.

Example:

  • Here, in line 6, there are no elements but length of the array is 4.
  • In line 7, array a has no elements and length is 0.
  • In line 8, array a is assigned one element 0 but the length of the array is set to 1001.

Sparse arrays are typically implemented in a slower, more memory-efficient way than dense arrays. The elements are looked up in such an array in as much time as by regular object property lookup.

Array Length Property

In JavaScirpt, the length property of an array specifies the number of elements in the array. This property is associated with every array in JavaScript, and it makes the array different from regular JavaScript objects.

The value of the Array Length is always one more than the highest index in the array.

Example:

[].length
["a","b","c"].length
  • Here, in line 1, the array has no elements.
  • In line 2, the array has three elements, so the highest index number will be 2.
  • Length of the array will be more than the highest index number, i.e. 2+1=3.

Another special feature of an array in JavaScript to maintain the length invariant is that if we set the length property of an array to a non-negative integer n smaller than its current value, then any array elements whose index is greater than or equal to n are deleted from the array automatically.

Example:

a = [1,2,3,4,5];
a.length = 3;
a.length = 0;
a.length = 5;
  • Here, in line 1, an array is assigned five elements.
  • In line 2, a has now only three elements as length of array is set to 3.
  • In line 3, array has no elements as all are deleted because length of array is set to 0.
  • In line 4, length of array is 5 but no elements are there(sparse array).

How to Add/Delete Array elements in JavaScript?

Previously, we have already learned to add elements to an array by just assigning values to the new indexes.

Example:

  • Here, an empty array a is created.
  • Array a is assigned with elements of value “zero” and “one” at index 0 and 1, respectively.

Another way of adding the value to an array is by using push() method. This method adds one or more value to the end of an array.

Example:

  • Here, first an empty array a is created.
  • Then a value “zero” is added at the end using push() method.
  • Again two more values “one” and “two” are added at the end using push() method.

Contrary to this method, we can use pop() method to remove the last element of an array, reducing the length of the array by 1.

Also for deleting array elements, we can use delete operator.

Example:

  • Here, after deleting operation delete a[2], array a has no element at index 2.
  • Also, array index 2 is not defined.
  • And the delete operation does not affect the array length.

However, we should note that deleting an array element makes the array sparse which means that there is a gap in the array and no elements of higher indexes are shifted to fill the gap.

How to use loops through Arrays in JavaScript?

In JavaScript, array or any iterable object can be looped through each elements using loops such as for/of loop.

Example:

  • Here, in line 6, an array is assigned with some string value.
  • In line 7, variable string is assigned with “” value.
  • In line 8, a for loop is used to iterate the elements to get the original value.

The built-in array iterator that for/of loop uses returns the elements of an array in ascending order. It returns undefined for any array elements that do not exist.

Another way of iterating the arrays is by using forEach() method, which actually passes the array index to the function as a second argument, which may be useful sometimes. Unlike for/of loop, this method do not invoke function for elements that do not exist.

We will discuss about the forEach() method in detail in the Array Methods part later.

What are Multidimensional Arrays in JavaScript?

In JavaScript, true Multidimensional Arrays are not supported but they can be achieved by approximating them with arrays of arrays.

For accessing the values of a multidimensional array, we can use the [] operator twice.

In the example given below, we will get an idea of creating, initializing, and performing operations on a multidimensional array.

Example:

Creating a Multidimensional Array

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let table = new Array(10);

for(let i = 0; i < table.length; i++){
    table[i] = new Array[10];
}

</script>
</head>
<body>
</body>
</html>
  • Here, the multidimensional array is created that will have 10 rows.
  • And each row will have 10 columns.

Initializing a Multidimensional Array

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

for(let row = 0; row < table.length; row++){
    for(let col = 0; col < table[row].length; col++){
        table[row][col] = row*col;
    }
}


</script>
</head>
<body>
</body>
</html>
  • Here, the multidimensional array is initialized.

Operating a Multidimensional Array

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

table[5][7]

</script>
</head>
<body>
</body>
</html>
  • Here, the multidimensional array is used to making a mathematical calculation.

Array Methods in JavaScript

In JavaScript, the methods defined by the Array Class are the most important and powerful part of the language. These methods enable a user to perform different operations using the basics syntax we learned till now. These methods are used to modify the array or leave them unchanged but are considered as a new array.

Iteration Methods of Array

Array Iteration Methods are mostly used to iterate arrays by passing array elements, in order, to a supplied function, they provide efficient ways to iterate, filter, test, map, and reduce arrays.

FOREACH()

The forEach() method iterates through an array, with invoking functions specified for each element.

  • A function is passed as the first argument to forEach().
  • Then forEach() invokes the passed function with three arguments, i.e. value of the array, index of the array element, and the array itself.
  • forEach() can be used with only one parameter too while ignoring the additional arguments.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let data = [1,2,3,4,5], sum = 0;
data.forEach(value => { sum += value; });

data.forEach(function(v, i, a) {
    a[i] = v + 1;
    
})

</script>
</head>
<body>
</body>
</html>

We should note that forEach() does not terminate the iteration before all the elements have been passed on to the function.

MAP()

The map() method passes each element of that array on which the map() method is invoked to the function the user specifies and it returns an array having the values returned by the function.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let data = [1,2,3];
a.map(x => x*x)

</script>
</head>
<body>
</body>
</html>

We should note that the map() method returns a new array, which means it does not modify the array it is invoked on.

FILTER()

The filter() method returns an array having a subset of the elements of the array which it is invoked on. The passed function should be a predicate, which means it should return true or false.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let data = [1,2,3];
a.filter(x => x < 3)
a.filter((x,i) => i%2 === 0)

let dense = sparse.filter(() => true); // To close the gaps in a sparse array

a = a.filter(x => x !== undefined && x !== null); // To close the gaps and remove undefined and null elements

</script>
</head>
<body>
</body>
</html>
EVERY() AND SOME()

The every() and some() methods are array predicates that applies a predicate function specified to the elements of array, then return true or false.

The every() method behaves like the mathematical “for all” quantifier while the some() method behaves like the mathematical “there exist” quantifier.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let a = [1,2,3,4,5];
a.every(x => x < 10)
a.every(x => x % 2 === 0)

let a = [1,2,3,4,5];
a.some(x => x % 2 === 10)
a.some(isNaN)

</script>
</head>
<body>
</body>
</html>
  • For every() method, it returns true for all values <10 and false when not all values are even.
  • For some() method, it returns true when a has some even numbers and false when a has no non-numbers.

Adding Arrays using concat()

In JavaScript, the concat() method creates and returns a new array that contains the elements of the original array on which it is invoked, followed by each of the arguments to concat().

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let a = [1,2,3,4,5];
a.concat(6,7,8) returns a[1,2,3,4,5,6,7,8]

</script>
</head>
<body>
</body>
</html>

We should note that concat() method makes a new copy of the array it is called on.

Stacks and Queues working with Array

In JavaScript, the push() and pop() methods enable a user to work with arrays while considering them as stacks.

  • The push() method appends one or more new elements at the end of the array and updates the length of the array.
  • The pop() method deletes the last element of the array and decreases the array length and returns the value that is removed.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let stack = [];
stack.push(1,2);
stack.pop();
stack.push(3);
stack.pop();
stack.push([4,5]);
stack.pop();
stack.pop();

</script>
</head>
<body>
</body>
</html>

We should note that the unshift() and shift() methods behave like push() and pop() methods, except that they insert and deletes the element from the beginning of an array rather than from the end.

We can use push() method for implementation in a queue to add elements at the end of the array and we can use shift() method to remove the element from the start of the array.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let s = [];
s.push(1,2);
s.shift();
s.push(3);
s.shift();
s.shift();

</script>
</head>
<body>
</body>
</html>

Subarray Operations

In JavaScript, arrays can be worked with different methods on contiguous regions, or subarrays or “slices” of an array. Also, we have another method called splice(), which is used for inserting or removing elements from an array on which it is invoked.

SLICE()

The slice() method returns a subarray. Its arguments determine the start and end of the slice to be returned.

  • The array returned has the elements specifies by the first argument and all the subsequent elements but not the elements specified by the second argument.
  • For only one argument, the returned array contains all the elements from start to end.
  • If any of the arguments is negative, it specifies an array element relative to the array length.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let s = [1,2,3,4,5];
s.slice(0,3); // returns [1,2,3]
s.slice(3); // returns [4,5]
s.slice(1,-1); // returns [2,3,4]
s.slice(-3,-2); // returns [3]

</script>
</head>
<body>
</body>
</html>
SPLICE()

The splice() method can insert new elements and delete elements from an array. This accordingly increases or decreases the indexes based on whether elements are inserted or deleted. This maintains the contiguousness of the array.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let s = [1,2,3,4,5,6,7,8];
s.splice(4); // returns [5,6,7,8]
s.splice(1,2); // returns [2,3]
s.splice(1,1); // returns [4]

</script>
</head>
<body>
</body>
</html>

Searching and Sorting methods in Arrays

In JavaScript, arrays can be searched using indexOf() and lastIndexOf() methods. Similarly, arrays can be sorted using the sort() method. We will discuss all these methods in detail using examples.

INDEXOF() AND LASTINDEXOF()

The indexOf() and lastIndexOf() methods search an element in an array with a specified value and return the index of the first element found or returns -1 if not found.

The indexOf() searches an array from start to end while the lastIndexOf() searches an array from end to start.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let s = [0,1,2,1,0];
a.indexOf(1) // Found at index 1
a.lastIndexOf(1) // Found at index 1
a.indexOf(3) // Not found: -1

</script>
</head>
<body>
</body>
</html>
SORT()

The sort() method sorts the elements of an array in a particular order and returns the sorted array. When no argument is passed in sort(), it sorts the array in alphabetical order by default.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let s = ["mumbai", "patna", "delhi"];
s.sort(); // returns s == ["delhi", "mumbai", "patna"]

</script>
</head>
<body>
</body>
</html>

Array-Like Objects in JavaScript

Till now we have learnt many aspects of Arrays in JavaScript, and we can conclude the following things about Arrays:

  • The length of an array is automatically updated when any news elements are added to the list.
  • The length of the array should always be greater than the number of elements in the list.
  • Arrays inherit the useful methods from the Array.prototype.
  • Array.isArray() always returns true for arrays.

These are the features that make an Array distinct from an Object in JavaScript. However, these are not the only essential features that define the array. It is fine to treat any Object with a numeric length property and corresponding non-negative integer properties as Array-like Objects.

Below is an example that shows a regular object is treated as an array-like object by adding some properties.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let a = {};

let i =0;
while (i < 10) {
    a[i] = i * 1;
    i++;    
}
a.length = i;

let total = 0;

for(let j = 0; j < a.length; j++){
    total += a[j];
}

</script>
</head>
<body>
</body>
</html>
  • Here, any empty object is created.
  • Then few properties are added to make it an array-like object.
  • Then the object is iterated as if it were a real array.

Strings and Arrays in JavaScript

In JavaScript, String behave as read-only arrays of UTF-16 Unicode characters. The individual characters of such a string can be accessed by using the square brackets instead of the charAt() method.

Example:

<html>
<head>
<title>Arrays in JavaScript</title>
<script type="text/javascript">

let s = "CODEDEC";

s.charAt(0)
s[1]

</script>
</head>
<body>
</body>
</html>
  • Here, String value is assigned to an array s.
  • Using s.charAt(0), we can access character C from the string.
  • Also, using square brackets s[2], we can access character D from the string.

Strings behave like arrays also mean that we can apply generic array methods to them. But we must also keep in mind that strings are immutable values, so they can only be treated as read-only arrays.

Also array methods like push(), sort(), reverse(), and splice() cannot be used for strings.

In the next section of the tutorial, we will discuss Functions in JavaScript and their uses and different properties that are used as a reusable code block that can be invoked anywhere in the program with some good examples for in-depth understanding.