Mastering Javascript Arrays: The Definitive Guide

Mastering Javascript Arrays: The Definitive Guide

Fix bugs faster! Log Collection Made Easy

Data is essential to all JavaScript applications. It determine what we see, hear and interact with when we open the app, and it must be stored properly to guarantee a smooth user experience. Specifically, the data must be a stored in a way that facilitates retrieval, manipulation and is efficient in storage usage. need data to represent information.

One of the most important prominent data structures in JavaScript is known as an Array. This is a collection of related elements, usually of the same data type, which can be accessed and manipulated using index numbers.

In this article, we will learn about Arrays and the operations we can perform with them. We will also explore the usage of many built-in array methods, with examples.

JavaScript Arrays

In JavaScript, arrays can be created using square brackets [] or the Array() constructor.

For example, the following code creates an array of strings:

let fruits = ["apple", "banana", "orange"];

We can access individual elements of an array using its index numbers. The index of the first element is always 0, and the index of the last element is always the length of the array, minus one. For example:

console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"
console.log(fruits[2]); // Output: "orange"

In JavaScript, arrays can also contain elements of different data types, such as numbers, strings, booleans, JavaScript objects, and even other arrays to create a nested array. For example:

let mixedArray = ["apple", 3, true, {name: "John"}, ["one", "two", "three"]];

To explain it visually, the image below shows how the elements of an array fit into the respective indexes.

JavaScript Array Length

The length of an array in JavaScript is the number of elements stored in the array. This is a property of the array object, and is accessible using the length property. The length property of an array is automatically updated when elements are added to or removed from the array.

Here’s an example of how to use the length property to determine the number of elements in an array:

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5

In this example, we have an array called numbers that contains five elements. We use the length property to get the number of elements in the array, which is 5.

As you can see, we are using JavaScript’s console log. As a JavaScript developer it’s important that you learn how to use and take advantage of JavaScript browser console, so we recommend you to check out the following article:

Discover the Hidden Potential: Advanced JavaScript Console Log for Developers

The length property can also be used to change the size of an array by assigning a new value to it. For example, if we assign a smaller value to the length property, the array will be truncated:

const numbers = [1, 2, 3, 4, 5];
numbers.length = 3;
console.log(numbers); // Output: [1, 2, 3]

In this example, we assign the value 3 to the length property of the numbers array. As a result, the last two elements of the array are removed, and the array now contains only three elements.

On the other hand, if we assign a larger value to the length property, the array will be extended, and the new elements will be set to undefined:

const numbers = [1, 2, 3, 4, 5];
numbers.length = 7;
console.log(numbers); // Output: [1, 2, 3, 4, 5, empty × 2]

In this example, we assign the value 7 to the length property of the numbers array. As a result, the array is extended with two new elements set to undefined.

It’s important to note that the length property does not always correspond to the number of defined elements in the array. For example, if we create an array with a length property of 5 but only define three elements, the length property will still be 5.

const numbers = [1, 2, 3];
numbers.length = 5;
console.log(numbers); // Output: [1, 2, 3, undefined, undefined]
console.log(numbers.length); // Output: 5

In this example, we create an array with three defined elements but then assign a length of 5. As a result, the last two elements of the array are set to undefined, and the length property is 5.

JavaScript Array Methods

JavaScript provides many built-in methods that can be used to manipulate arrays. Here’s a list of some of the most commonly used examples:

push() – When you want to add one or more elements to the end of an array, use the push() method. In the code snippet below, we add a new string, “kiwi”, at the end of the fruits array. The push() method modifies the original array.

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'kiwi']

pop() – The pop() method removes the last element of an array and returs it, thereby modifying the original array. In the code example below, we remove the string “orange” using the pop() method.

const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
console.log(removedFruit); // Output: 'orange'

shift() – While pop() removes the last element of the array, shift() helps you to remove the first element of an array and returns it. In the code example below, we have removed the first element, “apple”, from the array using the shift() method.

const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(fruits); // Output: ['banana', 'orange']
console.log(removedFruit); // Output: 'apple'

unshift() – This method helps add an element to an array, just like the push() method, but it also adds one or more elements to the beginning of an array.

Compare the code below with the example we have seen for the push() method. Now, the element “kiwi” gets added to the beginning of the array.

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits); // Output: ['kiwi', 'apple', 'banana', 'orange']

slice() – The slice() method returns a new array that contains a portion of the original array, and you can provide the parameters to indicate how to slice out the portion of the array. Please note, however, that the slice operation will not change the original array.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ['banana', 'orange']

splice() – The splice() method may sound similar to the slice() method, but they’re used for entirely different purposes. Whereas the slice() method returns a portion of the original array, the splice() method changes the content of an array by removing or replacing existing elements and/or adding new ones.

The parameters of the splice() method look like these:

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

Now, take a look at the code snippet below. The numbers.splice(2, 1) expression removes one element at the index 2.

const numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 1); // Removes 1 element at index 2
console.log(numbers); // Output: [1, 2, 4, 5]

numbers.splice(3, 0, 6, 7); // Adds 6 and 7 at index 3
console.log(numbers); // Output: [1, 2, 4, 6, 7, 5] 

concat() – The concat() method combines two or more arrays in a single array. Note that the input arrays remained unchanged.

const fruits = ['apple', 'banana'];
const moreFruits = ['orange', 'kiwi'];
const allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ['apple', 'banana', 'orange', 'kiwi']

reverse() – As the name suggests, the reverse() method reverses the order of elements in an array. It’s important to highlight the fact that this method changes the input array itself.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
console.log(fruits); // Output: ['kiwi', 'orange', 'banana', 'apple']

sort() – The sort() method sorts the elements of an array. It performs an ascending sort by default and converts the elements into strings while sorting. Sorting an array of string with the sort() method is straightforward.

const fruits = ['orange', 'apple', 'banana', 'kiwi'];
console.log(fruits); // Output: ['apple', 'banana', 'kiwi', 'orange']

However when you try to sort numbers with the sort() method, as in the case above, it may give you unexpected results like this:

const array1 = [1, 10, 5, 31, 100000];
console.log(array1); // [1, 10, 100000, 31, 5]

To fix this, you need to use a compare function and pass that as an argument to the sort() method.

const array1 = [1, 10, 5, 31, 100000];
array1.sort((a,b) => a-b);
console.log(array1); // [1, 5, 10, 31, 100000]

join() – The join() method converts an array to a string. To avoid confusing this method with the concat() method, where two or more array elements merge, you can pass a specifier to the join method.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const fruitString = fruits.join(', ');
console.log(fruitString); // Output: 'apple, banana, orange, kiwi'

indexOf() – It returns the index of the first occurrence of a specified element in an array.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const index = fruits.indexOf('banana');
console.log(index); // 1

lastIndexOf() – This array method returns the index of the last occurrence of a specified element in an array.

const fruits = ['apple', 'banana', 'orange', 'banana', 'kiwi'];
const index = fruits.lastIndexOf('banana');
console.log(index); // Output: 3

includes() – When you want to determine whether an array includes a specified element or not, use the includes() method. It will return the value ‘true’ whether the element is included or false.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const includesApple = fruits.includes('apple');
console.log(includesApple); // Output: true

const includesGrape = fruits.includes('grape');
console.log(includesGrape); // Output: false

This method it’s effective for checking if simple, primitive types are present in an array. However, for objects and arrays (complex types), includes() checks for reference equality, not content equality, meaning it looks for the exact same object in memory, not just an object with the same properties or values.

filter() – The filter() method creates a new array with all elements that pass the test you provide, but remember that you need to provide the test using a callback JavaScript function. In the example below, the test is designed to isolate the even numbers.

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
console.log(evenNumbers); // Output: [2, 4, 6]

map() – This creates a new array with the results of calling a function on every element in the original array. The callback function that invokes every array element can be anything that suits your use cases.

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = {
  return num * 2;
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

reduce() – This applies a function against an accumulator and each element in the array, to reduce it to a single value. The example below uses the reduce() method to accumulate the array elements to find their sum.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(acc, num) {
  return acc + num;
}, 0);
console.log(sum); // Output: 15

forEach() – You can iterate over array elements in several ways, and there are loops for it. You can also use the forEach() method, which executes a provided function once for each array element. It iterates over the elements, as we see in the example below.

const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(num) {
// Output:
// 1
// 2
// 3
// 4
// 5

every() – The every() method ascertains whether all elements in the array pass the test provided by a callback function. It returns true or false accordingly.

const numbers = [1, 2, 3, 4, 5];
const isGreaterThanZero = numbers.every(function(num) {
  return num > 0;
console.log(isGreaterThanZero); // Output: true

const isGreaterThanTwo = numbers.every(function(num) {
  return num > 2;
console.log(isGreaterThanTwo); // Output: false

some() – Unlike the every() method, the some() method tests whether at least one element in the array passes the test provided by a callback function. Again, it returns answers in true or false.

const numbers = [1, 2, 3, 4, 5];
const isGreaterThanFour = numbers.some(function(num) {
  return num > 4;
console.log(isGreaterThanFour); // Output: true

const isGreaterThanSix = numbers.some(function(num) {
  return num > 6;
console.log(isGreaterThanSix); // Output: false

find() – The find() method returns the first element in the array that satisfies a provided testing function. Otherwise, it returns undefined.

const numbers = [1, 2, 3, 4, 5];
const foundNumber = numbers.find(function(num) {
  return num > 2;
console.log(foundNumber); // Output: 3

const foundNegativeNumber = numbers.find(function(num) {
  return num < 0;
console.log(foundNegativeNumber); // Output: undefined

findIndex() – The findIndex() method returns the index of the first element in the array that satisfies a provided testing function. Otherwise, it returns -1.

const numbers = [1, 2, 3, 4, 5];
const foundIndex = numbers.findIndex(function(num) {
  return num > 2;
console.log(foundIndex); // Output: 2

const foundNegativeIndex = numbers.findIndex(function(num) {
  return num < 0;
console.log(foundNegativeIndex); // Output: -1

flat() – The flat() method creates a new array with all sub-array elements concatenated recursively up to the specified depth.

const nestedArray = [1, [2, [3, 4]]];
const flattenedArray = nestedArray.flat(2);
console.log(flattenedArray); // Output: [1, 2, 3, 4]

flatMap() – The flatMap() method maps each element using a mapping function, then flattens the result into a new array.

const numbers = [1, 2, 3, 4, 5];
const mappedAndFlattened = numbers.flatMap(function(num) {
  return [num * 2, num * 3];
console.log(mappedAndFlattened); // Output: [2, 3, 4, 6, 6, 9, 8, 12, 10, 15]

at() – The at() method is a relatively new addition to JavaScript, introduced in ECMAScript 2019. It allows you to retrieve an element from an array at a specific index, similar to using square bracket notation with the index.

However, at() also supports negative indexing and returns undefined for out-of-bounds indices instead of throwing an error.

Here’s the basic syntax of the at() method:
  • array: The array to retrieve the element from.
  • index: The index of the element to retrieve. This can be a positive or negative integer.

Here are a few examples to demonstrate the usage of the at() method:

const fruits = ['apple', 'banana', 'orange', 'pear'];

console.log(; // Output: 'apple'
console.log(; // Output: 'orange'
console.log(; // Output: 'pear'
console.log(; // Output: undefined
console.log(; // Output: undefined

JavaScript arrays FAQ and common operations

In this FAQ section, we’ll explore some common questions about JavaScript arrays and learn about the common operations you can perform with them.

What is a JavaScript Array?

A JavaScript Array is an object that can hold multiple values of different types. It is an ordered list of elements, identified by their index. Arrays in JavaScript can contain any combination of numbers, strings, objects, or even other arrays. This flexibility makes arrays a powerful tool for organizing and manipulating data.

How to declare an array in JavaScript?

Declare an array in JavaScript with square brackets, like let myArray = [1, 2, 3];, or use the Array constructor, such as let myArray = new Array(1, 2, 3);.

let myArray = [1, 2, 3]; // Using square brackets
let anotherArray = new Array(1, 2, 3); // Using Array constructor
console.log(myArray); // Outputs: [1, 2, 3]
console.log(anotherArray); // Outputs: [1, 2, 3]

How do I add elements to a JavaScript array?

To add elements to an existing array, JavaScript provides several array methods. One method is push(), which adds one or more elements to the end of the array. For example, to add a new element to an array called myArray, you can use the following code: myArray.push("newElement");

Another method is unshift(), which adds one or more elements to the beginning of the array. The existing elements are shifted to higher indices. Here’s an example: myArray.unshift("newElement");

How to remove element from array in JavaScript?

Remove an element from an array in JavaScript by using splice(index, 1) for a specific index value, or filter() to conditionally remove elements. For example, array.splice(2, 1); removes the third element.

Using splice

let myArray = ['a', 'b', 'c'];
myArray.splice(1, 1); // Removes the element at index 1 ('b')
console.log(myArray); // Outputs: ['a', 'c']

Using filter

let myArray = ['a', 'b', 'c', 'b'];
myArray = myArray.filter(element => element !== 'b'); // Removes all instances of 'b'
console.log(myArray); // Outputs: ['a', 'c']

How to sort an array in JavaScript?

To sort an array in JavaScript, you can use the sort() method, which can optionally take a compare function as an argument. This function is often provided as a lambda (arrow) function, and determines the sort order based on the return value. For numerical sorting, the lambda function typically subtracts one element from another:

let numbers = [3, 1, 4, 2];
numbers.sort((a, b) => a - b); // Sorts the array numerically in ascending order
console.log(numbers); // Outputs: [1, 2, 3, 4]

How to find array length in JavaScript?

Determine the length of an array in JavaScript using the length property. For example, console.log(myArray.length); returns the number of elements in myArray.

let myArray = [1, 2, 3, 4, 5];
console.log(myArray.length); // Outputs the length of the array: 5

How to check if an array is empty JavaScript?

To check if an array is empty in JavaScript use the length property, evaluating array.length === 0. If true, the array is empty.

let myArray = [];
if (myArray.length === 0)
    console.log("Array is empty")
    console.lo("Array is not empty")

How can I merge multiple arrays in JavaScript?

Merge multiple arrays in JavaScript with the concat() method. For instance, const mergedArray = array1.concat(array2, array3); combines array1, array2, and array3.

let array1 = [1, 2];
let array2 = [3, 4];
let mergedArray = array1.concat(array2); // Merges array1 and array2
console.log(mergedArray); // Outputs: [1, 2, 3, 4]

How do I access elements in a JavaScript array?

Access elements in a JavaScript array using bracket notation with indices. For example, const element = array[index]; retrieves the element at index position from the array.

let myArray = ['a', 'b', 'c'];
console.log(myArray[0]); // Outputs the first element: 'a'
console.log(myArray[1]); // Outputs the second element: 'b'

How to convert string to array in JavaScript?

Convert a string to an array in JavaScript using split(). For a comma-separated string, use const array = string.split(',');.

let myString = "a,b,c";
let myArray = myString.split(","); // Splits the string into an array
console.log(myArray); // Outputs: ['a', 'b', 'c']

How to convert a JavaScript array to string?

Convert a JavaScript array to a JavaScript string with join(). For example, const string = array.join(', '); joins array elements with a comma and a space.

How to remove duplicates in array JavaScript?

To remove duplicates from an array in JavaScript, use [ Set(array)]. This creates a set with unique values and then converts it back to an array.

let myArray = [1, 2, 2, 3, 3, 3, 4];
let uniqueArray = [ Set(myArray)]; // Removes duplicates
console.log(uniqueArray); // Outputs: [1, 2, 3, 4]

How to find an item in a JavaScript Array?

To find an item in a JavaScript array, use the find() or includes()method. The find() returns the first element that satisfies a provided testing function. If no array item satisfy the testing function, it returns undefined. Here’s an example:

let array = [1, 2, 3, 4, 5];
let foundItem = array.find(element => element > 3); // Finds the first element greater than 3
console.log(foundItem); // Outputs: 4

Use the includes() method to find out if an item exists in a JavaScript array. This method checks if the array contains a specific element and returns true if it does, or false if it does not. However, includes() only checks for the presence of an element.

let myArray = [1, 2, 3, 4, 5];
let hasThree = myArray.includes(3); // Checks if '3' is in the array
console.log(hasThree); // Outputs: true

How to iterate a JavaScript array?

To iterate over a JavaScript array, you can use several methods, including forEach(), for loops, or for…of loops. Here’s how each method works:

Using forEach():

let myArray = [1, 2, 3];
myArray.forEach(element => console.log(element)); // Iterates and logs each element

Using a for loop:

for (let i = 0; i < myArray.length; i++) {
    console.log(myArray[i]); // Accesses each element by index

Using a for...of loop:

for (let element of myArray) {
    console.log(element); // Directly accesses each element


That’s all for now. We hope it was useful and has given you a launchpad to start using the array methods. As a JavaScript developer, you don’t need to remember all the syntaxes of the Array methods. However, you must know their usage to ensure you maximise their benefits and deploy them at the right times.

Expect the Unexpected! Debug Faster with Bugfender

Trusted By


Already Trusted by Thousands

Bugfender is the best remote logger for mobile and web apps.

Get Started for Free, No Credit Card Required