JavaScript Arrays       

Author:

JavaScript arrays are types of objects that are data collections, but you should think of them more as displays. This distinction was made because JavaScript also has a different-syntax data collection form called objects. 

JavaScript offers a wide range of capabilities and objects for your software development, similar to many other programming languages. Nearly everything in JavaScript is an object, each with a unique set of strong advantages. For instance, an Array is among the most popular JavaScript objects.

Let’s discuss in detail what JavaScript Arrays are and the various methods that can make a developer’s life easier.

What Are JavaScript Arrays? 

An array, to start, can include values of various types. You could, for instance, store elements of the kinds such as number, string, boolean, and null in an array. An array’s size is automatically and dynamically expanding. In other words, it’s not necessary to declare the array size in advance.  

Since JavaScript arrays do not refer to associative arrays, it is impossible to access array items using random strings as indexes; instead, nonnegative numbers (or their corresponding string forms) must be used.

Square brackets are used to indicate how to obtain an array’s elements. The array’s elements are each given an index. An array’s first index is always zero by default.

The index value is enclosed in a set of square brackets, as in veggies [0], to retrieve a specific element from an array. To avoid any misunderstanding, consider the index to be the number of elements to skip, counting backwards from the array’s beginning.

JavaScript arrays are employed to examine and manage a large quantity of data belonging to a similar type. An array is used to hold the data. One variable name is used to access the JavaScript array.  

To access specific array elements, utilise the index values. An array’s data is often processed using a loop statement, which changes the index value inside the loop’s body to access all of the array’s elements. Processing information in an array requires a few statements. As a result, employing arrays to process data in a programme makes it smaller.

Types of JavaScript Arrays  

There are four types of JavaScript Arrays. They are as follows:

  1. One-Dimensional Array
  2. Two-Dimensional Array
  3. Three-Dimensional Array (Multi-Dimensional Array)
  4. Character Arrays

One-Dimensional Array  

A linear array is another name for a one-dimensional array. It has only a single row or one column in it. We know that an array divides a contiguous memory block into equal sections. 

One component of the JavaScript array is represented by each component of the memory block. Element numbers in JavaScript range from 0 to n-1. The ‘n’ stands for the JavaScript array’s overall element count.  

Two-Dimensional Array 

Two-dimensional arrays are used to express the array’s elements in the structure of rows and columns, which are then used to represent what is called a matrix. Two-dimensional arrays utilise two subscripts to declare the array’s elements.

Three-Dimensional Array (Multi-Dimensional Array)

The total quantity of matrix tables is represented by a multidimensional array. When creating two or more than two tables of mixture components for declaring the usable array elements, a three-dimensional array is employed.

Character Arrays 

Similar to how a numeric array is a series of numbers, a character array represents a sequence of characters. Short passages of text are frequently stored as character vectors. A string array serves as a storage space for text fragments. A set of functions are available for handling text as data in string arrays.

Pros and Cons of Using Arrays 

It’s essential to understand the pros and cons of arrays before using them in programming.

Pros 

  • Every element of an array is given a consistent memory address. So memory overflow is prevented.
  • They keep comparable information of the same kind.
  • In comparison to other data structures, array iteration occurs more quickly.
  • Once declared, an array may be used repeatedly. This makes code easier to read.
  • When you are aware of the total number of elements, they save memory space. 
  • They implement more data structures, such as stacks, trees, clusters, and graphs.
  • They keep the components in two-dimensional or multidimensional arrays of various sizes.  

Cons 

  • The fact that an array’s elements are kept in adjacent memory places makes inserting and removing them expensive.
  • Since an array does not check the indexes when compiled, errors appear at runtime rather than during compilation.
  • An array’s initial memory allocation can neither be increased nor lowered. 
  • Memory space can be wasted by assigning more memory than is necessary.
  • If you wish to include an array, you must first choose how many elements you would like to store. Once it has been declared, adding new or additional values is impossible.

JavaScript Array Methods 

Array in JavaScript lets you store several elements at once. Array methods, along with their attributes, are discussed below.

  • JavaScript Array length()

This method provides the array’s element count. The 32-bit, unsigned integer that the JavaScript array length property produces indicates how many elements are in an array.

Syntax: 

array.length   

Example: 

<html>
   <head>
      <title>JavaScript Array length Property</title>
   </head>
   
   <body>   
      <script type = "text/JavaScript">
         var arr = new Array( 40, 50, 60 );
         document.write("arr.length is : " + arr.length); 
      </script>      
   </body>
</html>

Output: 

arr.length is : 3 

  • JavaScript Array map() 

The map() method calls a function for every array element and then returns the results in a new array.

Syntax: 

arr.map(callback(currentValue), thisArg)

Example: 

let numbers = [3, 5, 7, 9, 11];

// function to return the square of a number
function square(number) {
  return number * number;
}

// apply square() function to each item of the numbers list
let square_numbers = numbers.map(square);
console.log(square_numbers);

Output: 

[9, 25, 49, 81, 121]

  • JavaScript Array of() Method

The of() method builds a new instance of an array from the supplied inputs. 

Syntax: 

array.of(element0, element1, …, elementN)

Example: 

// creating an array one element
let numbers = array.of(3);  

console.log(numbers); // [ 3 ]

// creating an array with three string elements
let vegetables = array.of("Carrot", "Peas", "Onion"); 

console.log(fruits); // 

Output:

[ ‘Carrot’, ‘Peas’, ‘Onion’ ]

  • JavaScript Array pop()

The pop() method retrieves the element that was removed last from an array.

Syntax: 

arr.pop()

Example: 

let cities = ["Dublin", "Amsterdam", "Berlin", "Paris"];

// remove the last element
let removedCity = cities.pop();

console.log(cities)         // ["Dublin", "Berlin", "Berlin"]
console.log(removedCity);   

Output:

Paris

  • JavaScript Array concat()

The concat() method creates a new array by combining two or various values/arrays.

Syntax: 

array.concat(value1, value2, …, valueN)

Example: 

let primeNumbers = [11, 13, 17, 19]
let evenNumbers = [2, 4, 6, 8]

// join two arrays 
let joinedArrays = primeNumbers.concat(evenNumbers);
console.log(joinedArrays);

Output:

[

  11, 13, 17, 19,

  2, 4, 6, 8 

]

  • JavaScript Array Constructor 

The constructor property brings back the constructor function for arrays.

Syntax: 

arr.constructor

Example:

let languages = ["JavaScript", "C++", "Python"];
let constructor = languages.constructor;
console.log(constructor)

Output:

[Function: Array] 

  • JavaScript Array copyWithin()

The copyWithin() method copies elements from arrays from a specific position to some other in the present array.

Syntax: 

arr.copyWithin(target, start, end)

Example: 

let words = ["kite", "ball", "bus", "car"];

// copies element from index 0 to index 3 
words.copyWithin(3, 0);

// modifies the original array 
console.log(words);

Output: 

[ ”kite”, ”ball”, ”bus”, ”kite” ]

  • JavaScript Array entries()

The entries() method retrieves a brand new array Iterator element consisting of key pairs for every array index.

Syntax: 

arr.entries()

Example:

// defining an array named birds
const birds = ["Crow", "Eagle", "Kingfisher"];

// array iterator object that contains
// key-value pairs for each index in the array
let iterator = alphabets.entries();

// iterating through key-value pairs in the array
for (let entry of iterator) {
  console.log(entry);
}

Output: 

[ 0, ‘Crow’ ]

[ 1, ‘Eagle’ ]

[ 2, ‘Kingfisher’ ]

  • JavaScript Array every()

The JavaScript Array every() method helps to check if all array elements are passing a given test function. 

Syntax: 

arr.every(callback(currentValue), thisArg)

Example: 

function checkAdult(age) {
    return age >= 21;
}

const ageArray = [35, 28, 20, 25, 11];
let check = ageArray.every(checkAdult); // false

if (!check) {
    console.log("All members should be at least 21 years old.")
}

// using arrow function
check1 = ageArray.every(age => age >= 21); // false
console.log(check1);

Output:

false

  • JavaScript Array fill()

The fill() method retrieves an array by filling every element with a specific value.

Syntax: 

arr.fill(value, start, end)

Example:

// defining an array 
var fruits = ['Strawberry', 'Cherry', 'Grape'];

// filling every element of the array with 'Banana'
fruits.fill("Banana");
console.log(fruits);

Output: 

// [ ‘Banana’, ‘Banana’, ‘Banana’ ]

  • JavaScript Array filter()

The filter() method retrieves a brand new array with all the elements that are successful in passing the test outlined by the given function.

Syntax: 

arr.filter(callback(element), thisArg)

Example:

let numbers = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

// function to check even numbers
function checkEven(number) {
  if (number % 2 == 0)
    return true;
  else
    return false;
}

// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);

Output: 

[ 12, 14, 16, 18, 20 ]

  • JavaScript Array find()

The find() method retrieves the value of the very first array element which satisfies the given test function.

Syntax: 

arr.find(callback(element, index, arr),thisArg)
Example:

let numbers = [1, 3, 6, 9, 8];

// function to check even number
function isEven(element) {
  return element % 2 == 0;
}

// get the first even number
let evenNumber = numbers.find(isEven);
console.log(evenNumber);

Output: 

6

  • JavaScript Array findIndex()

The findIndex() method helps to retrieve the index related to the initial array element that is responsible for satisfying the given verifying function, or else the value returns -1.

Syntax: 

arr.findIndex(callback(element, index, arr),thisArg)

Example:

// function that returns odd number
function is Odd(element) {
  return element % 2 !== 0;
}

// defining array of integers
let numbers = [2, 6, 1, 3, 5];

// retrieves the index of the first odd number present in the array
let firstOdd = numbers.findIndex(isOdd);

console.log(firstOdd);

Output: 

2

  • JavaScript Array flat()

The flat() method helps create a new array by flattening a nested array up to a specific depth.

Syntax: 

arr.flat(depth)

Example: 

// 3 nested arrays 
let numbers = [11, 12, [13, 14, [15, 16, [17, 18]]]];

// reducing nesting with flattening array to depth 1 
let flattenArray = numbers.flat(1);

// new flatten array
console.log(flattenArray);

Output:

// [ 11, 12, 13,14, 15, 16, 17, 18 ]

  • JavaScript Array flatMap()

The flatMap() method initially maps every element of an array utilising a mapping function and then flattens it to create a new array.

Syntax: 

arr.flatMap(callback(currentValue),thisArg)

Example: 

// defining an array
let numbers = [2, 3, 4, 5, 6];

// every element in the array is squared and then flattened
 resultingArray = numbers.flatMap((x) => [x ** 2]);

console.log(resultingArray);

Output:

[4, 9, 16, 25, 36]

  • JavaScript Array forEach()

The forEach() method carries out a given function for every array element.

Syntax: 

arr.forEach(callback(currentValue), thisArg)

Example: 

let numbers = [1, 2, 3, 4, 6];

// function to compute square of each number
function computeSquare(element) {
  console.log(element * element);
}

// compute square root of each element
numbers.forEach(computeSquare);

Output:

1

9

16

36

  • JavaScript Array.from() 

The from() method helps to create a new array from an existing array or an iterable object.

Syntax: 

Array.from(arraylike, mapFunc, thisArg)

Example:

// creating a new array from string
let newArray = Array.from("ghi");
console.log(newArray);

Output:

[ ‘g’, ‘h’, ‘i’ ] 

  • JavaScript Array includes()

The includes() method verifies if an array consists of a specific element or not.

Syntax: 

arr.includes(valueToFind, fromIndex)

Example:

// defining an array
let languages = ["JavaScript", "Java", "C++"];

// checking whether the array contains 'Java'
let check = languages.includes("Java");

console.log(check);

Output: 

true

  • JavaScript Array indexOf()

The indexOf() method retrieves the first index of an occurrence in an array’s element, or -1 if it is unable to be found.

Syntax: 

arr.indexOf(searchElement, fromIndex)

Example:

let languages = ["Java", "JavaScript", "C++", "JavaScript"];

// get the index of the first occurrence of "JavaScript"
let index = languages.indexOf("JavaScript");
console.log(index);

Output: 

1

  • JavaScript Array isArray()

The isArray() method assists in checking whether the verified argument is an array or not.

Syntax: 

Array.isArray(value)

Example:

let arrNumbers = [11, 12, 13, 14];

// checking whether arrNumbers is an array or not 
console.log(Array.isArray(arrNumbers));

let txt = "JavaScript";  

// checking whether txt is an array or not
console.log(Array.isArray(text)); 

Output:

// true

// false 

  • JavaScript Array join()

The join() method retrieves a new string with the help of concatenating every element in an array which is separated by a specific separator.

Syntax: 

arr.join(separator)

Example:

let message = ["Python", "is", "fun."];

// join all elements of array using space
let joinedMessage = message.join(" ");
console.log(joinedMessage);

Output: 

Python is fun.

  • JavaScript Array keys()

The keys() method retrieves a brand new array Iterator object which contains the keys for every element in the array.

Syntax: 

arr.keys()

Example:

let alphabets = ["X", "Y", "Z"];

// returns an Array Iterator object that contains the keys
let iterator = alphabets.keys();

// looping through the Iterator object
for (let key of iterator) {
  console.log(key);
}

Output:

0

1

2

  • JavaScript Array lastIndexOf()

The lastIndexOf() approach retrieves the index of the last occurrence of a specific element in an array.

Syntax: 

arr.lastIndexOf(searchElement, fromIndex)

Example: 

let priceList = [11, 18, 22, 31, 10, 31, 64];

// finding the index of the last occurrence of 31
let lastIndex = priceList.lastIndexOf(31);

console.log(lastIndex); 

Output: 

5

  • JavaScript Array push()

The push() method helps to add zero or various more elements at the end of the array.

Syntax: 

arr.push(element1, element2, …, elementN)

Example:

let city = ["New York", "Madrid", "Paris"];

// add "London" to the array
city.push("London");

console.log(city);

Output: 

[ ‘New York’, ‘Madrid’, ‘Paris’, ‘London’ ]

  • JavaScript Array reduce()

The reduce() method accomplishes a reducer function for every element in the array and retrieves a single output value. 

Syntax: 

arr.reduce(callback(accumulator, currentValue), initialValue)

Example:

const message = ["Python ", "is ", "fun."];

// function to join each string elements
function joinStrings(accumulator, currentValue) {
  return accumulator + currentValue;
}

// reduce join each element of the string
let joinedString = message.reduce(joinStrings);
console.log(joinedString);

Output: 

Python is fun.

  • JavaScript Array reduceRight()

The reduceRight() method compresses the array into a single value by carrying out a callback function for two values of the array from right to left.

Syntax: 

arr.reduceRight(callback(accumulator, currentValue), initialValue)

Example:

let numbers = [1, 2, 3, 4, 5];

// function that adds last two values of the numbers array
function sum_reducer(accumulator, currentValue) {
  return accumulator + currentValue;
}

// returns a single value after reducing the numbers array
let sum = numbers.reduceRight(sum_reducer);

console.log(sum);

Output: 

15

  • JavaScript Array reverse()

The reverse() method retrieves the array in reverse order.

Syntax: 

arr.reverse()

Example:

let numbers = [1, 2, 3, 4, 5, 6];

// reversing the numbers array
let reversedArray = numbers.reverse();
console.log(reversedArray);

Output: 

[6, 5, 4, 3, 2, 1 ]

  • JavaScript Array shift()

The shift() method removes the first element of an array and retrieves that element.

Syntax: 

arr.shift()

Example:

let languages = ["English", "Java", "C++", "JavaScript"];

// removes the first element of the array
let first = languages.shift();
console.log(first);
console.log(languages);

Output: 

English

[ ‘Java’, ‘C++’, ‘JavaScript’ ]

  • JavaScript Array slice()

The slice() method retrieves a shallow copy of a part of an array into a new object.

Syntax: 

arr.slice(start, end)

Example:

let numbers = [2, 3, 5, 7, 11, 13, 17];

// create another array by slicing numbers from index 3 to 5
let newArray = numbers.slice(3, 6);
console.log(newArray);

Output: 

[ 7, 11, 13 ]

  • JavaScript Array some()

The some() method checks whether any of the elements in an array pass the given evaluation function.

Syntax: 

arr.some(callback(currentValue), thisArg)

Example:

// a test function: returns an even number
function isEven(element) {
  return element % 2 === 0;
}

// defining an array
let numbers = [11, 13, 12, 15, 14];

// checks whether the numbers array contain at least one even number
console.log(numbers.some(isEven));

Output: 

true

  • JavaScript Array sort()

The sort() method helps sort the items of an array in a specified order, either in ascending or descending order.

Syntax: 

arr.sort(compareFunction)

Example:

let city = ["Berlin", "Barcelona", "Paris", "Kathmandu"];

// sort the city array in ascending order
let sortedArray = city.sort();
console.log(sortedArray);

Output: 

[ ‘Barcelona’, ‘Berlin’, ‘Kathmandu’, ‘Paris’ ]

  • JavaScript Array splice()

The splice() method retrieves an array by adding or removing its elements in a given place.

Syntax: 

arr.splice(start, deleteCount, item1, …, itemN)

Example:

let prime_numbers = [2, 3, 5, 7, 9, 11];

// replace 1 element from index 4 by 13
let removedElement = prime_numbers.splice(4, 1, 13);
console.log(removedElement);
console.log(prime_numbers);

Output: 

[ 9 ]

[ 2, 3, 5, 7, 13, 11 ]

  • JavaScript Array toLocaleString()

The toLocaleString() method retrieves a string that represents the elements of an array in a specific locale.

Syntax: 

arr.toLocaleString(locales, options)

Example:

let array1 = ["Germany", 1];

// returns string representation of array
let stringFromArray = array1.toLocaleString();

console.log(stringFromArray);

Output:  

Germany,1 

  • JavaScript Array toString()

The toString() method retrieves a single string formed by the elements of an array.

Syntax: 

arr.toString()

Example:

// defining an array
let items = ["Python", 1, "a", 3];

// returns a string with elements of the array separated by commas
let itemsString = items.toString();

console.log(itemsString);

Output: 

Python,1,a,3

  • JavaScript Array unshift()

The unshift() method enables one to add one or more elements at the beginning of a particular array and retrieves the new length of the array.

Syntax: 

arr.unshift(element1, element2, …, elementN)

Example:

let languages = ["Java", "Python", "C++"];

// add "JavaScript" at the beginning of the array
languages.unshift("JavaScript");
console.log(languages);

Output:  

[ ‘JavaScript’, ‘Java’, ‘Python’, ‘C++’ ]

  • JavaScript Array values()

The values() method retrieves a new array iterator object that consists of the values for every index in the array.

Syntax: 

arr.values()

Example:

let languages = ["JavaScript", "Python", "C++"];

// returns an Array Iterator object that contains values
let iteratorObject = languages.values();

// looping through iterator
for (let value of iteratorObject) {
  console.log(value);
}

Output:

JavaScript

Python

C++

Wrapping Up  

You can store components of many types together in an array since JavaScript arrays are simply unique objects. Arrays are essentially singular objects that contain numerous stored values in a list; they are commonly referred to as “list-like objects.” 

The only difference between array objects and other types of values is that by using array objects, we can get each individual value individually and perform incredibly useful and efficient operations on the list, such as looping through it and applying the same operation to each value.

Learn some coding basics for free

If you want to learn some of the basics of JavaScript for free, try this free 5 Day Coding Challenge. On it, you will learn the basics of HTMLCSS and JavaScript. It takes just one hour a day over five days. Register now through the form below. Alternatively, if you want to learn full-stack software development, you can read more about our programme here.

What is an AI Developer & How to Become One?

Right now, the world is witnessing an artificial intelligence technological revolution, and AI Developers are at the forefront. AI developers are those who design, develop, and deploy AI-powered solutions. They are shaping the technological future by creating intelligent systems and applications. We look into the world of AI developers, exploring their roles, skills, and the […]

Systems Analyst: A Guide 

A system analyst looks after a company’s computer systems and network and ensures they meet its goals. They ensure that the infrastructure, computers and other systems work efficiently.  Who do you think takes care of all the systems in a company and plans everything out for a firm to meet its needs? Who do you […]

What Does a .NET Developer Do & How to Become One?

.NET developers are essential in the realm of software development. They are in charge of planning, creating, testing, and managing software applications built with the Microsoft .NET framework. As a result, they are in high demand and can command substantial wages in the tech business. In this blog, we will look at what a .NET developer […]