DEV Community

Bolaji Bolajoko
Bolaji Bolajoko

Posted on

Demystifying JavaScript Arrays: A Comprehensive Guide for Beginners and Intermediates

Introduction

JavaScript arrays are variable which can hold more than one value or items of different data types under a single variable name. An array can contain a mixture of numbers, strings and any other JavaScript data types like objects, booleans and even null. You can think of JavaScript array as a big container that helps us to hold different household items.

Much like how you can organize, manipulate, and transform household items, JavaScript arrays allow you to manage data items efficiently. You can easily access, modify, and rearrange the items stored within an array. This ability to work with arrays empowers JavaScript developers to handle data in a structured and dynamic manner, making arrays a fundamental tool in JavaScript programming.

Understanding Arrays

When we have list of items, let's say a list of fruits, storing the items in a regular (scalar) variable will look something like this:

const fruit1 = "Orange";
const fruit2 = "Banana";
const fruit3 = "Apple";
Enter fullscreen mode Exit fullscreen mode

Here comes the problem: if the list of fruits we are having is in hundreds, managing the list of fruit will become daunting and complicated. Storing items in a regular variable does not give us the ability to store different data types as well, thereby limiting the types of items that can be stored in it.

Arrays give us the privilege to store the list of fruit under a single variable name, making it easy for us to to access and manipulate the items. Storing the fruit items will look something like this:

const fruit = ["Orange", "Banana", "Apple"]; // storing list of fruits
Enter fullscreen mode Exit fullscreen mode

Arrays also give us the ability to store different data-types (including arrays themselves) under a single variable name.

const mixedData = [23, "Bob", { key: "value"}, [], false]; // storing mutiple data-types 
Enter fullscreen mode Exit fullscreen mode

Creating Arrays

There are two methods used to create an array:

  1. Constructor method

  2. Array Literals

The syntax is:

const newArray = new Array(); // constructor method
const newArray = [ ]; // literal method
Enter fullscreen mode Exit fullscreen mode

Most of the time, the second method and syntax are used. Throughout this article, we will be making use of the second syntax.

An array that doesn't have any items in it is said to be an empty array. In the code sample above, we've only created an empty array, because we have not supplied any item into the square brackets and the constructor method. We can add items to the array by entering a list of items we want between the square brackets separated by a commas.

const planet = ["Mercury", "Mars", "Pluto", "Jupiter"]
Enter fullscreen mode Exit fullscreen mode

You can supply a trailing comma after the last item in the list.

Array indexing and Accessing Elements

When we create an array the element positions start from index of zero. We count the array items from zero up to the last item in the list.

const fruits = ["Orange", "Banana", "Apple"]

// 0 position element -> Orange
// 1 position element -> Banana
// 2 position element -> Apple
Enter fullscreen mode Exit fullscreen mode

The position number is often referred to as the index number.

We can access each element in the array using the [ ] notation along with the index number. This is achieved by inserting the index number within the square brackets.

Syntax:

// accessing element in an array
myArray[indexPosition]
Enter fullscreen mode Exit fullscreen mode
const fruits = ["Orange", "Banana", "Apple"]

console.log(fruits[0]) // Orange
console.log(fruits[1]) // Banana
console.log(fruits[2]) // Apple
Enter fullscreen mode Exit fullscreen mode

The square brackets and the index number can also be used to change an element in the array. Similarly, they can be used to add a new element to the array.

const fruits = ["Orange", "Banana", "Apple"]


// changing element in the array
fruits[1] = "Cherry"; // changing the element at position index 1
console.log(fruits) // new version of fruits: ["Orange", "Cherry", "Apple"]


fruits[3] = "Mango"; // adding new element to the array at position 3
console.log(fruits); // new version of fruits: ["Orange", "Cherry", "Apple", "Mango"]
Enter fullscreen mode Exit fullscreen mode

In example above, we access the second element in the array with the index number [1] and we assign a new element the position.

In the second part of the code, we try to access the fourth element in the array which was not there, then immediately we assign an element to it. The position index [3] is created by JavaScript, and the element Mango is inserted into the list, taking up the fourth position.

Accessing an index that is not in the array will return undefined.

Array Length and Manipulation

To get the length of an array, we can can use the length property on the array variable. This property returns an integer number signifying the length of the array (the number of elements in the array).

const person = ["Alice", "Bob", "John", "Jack"];
let total = person.length;
console.log("Total number of element in Person array is " + total);
// Output: Total number of element in Person array is 4
Enter fullscreen mode Exit fullscreen mode

Accessing the last element in the array: We can obtain the last index element in the using the length property

let lastItem = person[person.length - 1]; // Jack
Enter fullscreen mode Exit fullscreen mode

The length properties is equally writable; we can increase and decrease it by assigning a new value to it. If we increase the length, an empty items will be created. Accessing this empty items will return undefined. Conversely, if we decrease the length, the array will be truncated. The process is irreversible.

const evenNum = [2, 4, 6, 8, 10];
evenNum.length = 6; // increasing the length

console.log(eveNum); // [ 2, 4, 6, 8, 10, <1 empty-items> ]
Enter fullscreen mode Exit fullscreen mode
const evenNum = [2, 4, 6, 8, 10];
evenNum.length = 3; // decrease the array length
console.log(evenNum); // [ 2, 4, 6];
Enter fullscreen mode Exit fullscreen mode

JavaScript provides different ways to manipulate array elements:

  • Using array methods such as pop, push, shift, unshift among others.

  • Updating elements by directly assigning new values. (as discussed in the previous section).

In the subsequent section, we will be discussing the various array methods provided by JavaScript.

Looping through Arrays

There are situations where we need to iterate through all the items in an array. Attempting to access all the items in an array using direct index numbers can be tedious and time-consuming. JavaScript provides us with ways to go through all the items in an array, which includes: for loop and the for...of loop

For Loop

You can use for loop to iterate over the elements of an array. It allows you to perform operations on each element in the array. Here is a basic example of how you can use a for loop to iterate over the elements of an array:

const fruits = ["apple", "banana", "orange", "grape", "mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// output
/* apple
   banana
   orange
   grape
   mango
 */
Enter fullscreen mode Exit fullscreen mode

List of fruits

In this example, the loop iterates through each element in the array. The loop control count variable i is used as an index to access each item in the array using fruits[i].

The loop terminates when i equals to the length of the array ensuring all the items are iterated over.

For...of Loop

for...of loop is a modern approach to iterates over the element in an array. It is concise and readable, making it more preferable than the traditional for loop.

const fruits = ["apple", "banana", "orange", "grape", "mango"];

for(let fruit of fruits){
    console.log(fruit);
}

// output
/*
    apple
    banana
    orange
    grape
    mango

*/
Enter fullscreen mode Exit fullscreen mode

In the example, the for...of loop iterates over each element in the fruits array. During each iteration, the value of the current element is assigned to the loop variable fruit, and the loop body is executed. The loop automatically handles the index and provides direct access to the element

The for...of loop abstracts away the need for maintaining an index and provides a clean and straightforward way to work with iterable objects like arrays, strings and more. It is especially useful when you're more interested in the values themselves rather than the index for your operations.

Array Methods

JavaScript provides us with various predefined actions that can be performed on arrays. In this this section, we will be looking at most important arrays methods.

push() :

  • Adds one or more elements to the end of an array.

  • Returns the new length of the array.

const numbers = [1, 2, 3];
numbers.push(4, 5);
console.log(numbers) // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

pop() :

  • Removes the last element from the end of an array.

  • Returns the removed element.

const fruits = ["apple", "mango", "orange"];
const removedFruit = fruits.pop();

console.log(fruits) // Output: ["apple", "mango"]
console.log(removedFruit); // Output: orange
Enter fullscreen mode Exit fullscreen mode

unshift() :

  • Adds one or more elements to the beginning of an array.

  • Returns the new length of the array.

const colors = ["yellow", "green", "blue"];
colors.unshift("red");


console.log(colors) // Output: ["red", "yellow", "green", "blue"]
Enter fullscreen mode Exit fullscreen mode

shift() :

  • Remove element from the beginning of an array.

  • Returns the removed element.

const animals = ["lion", "tiger", "elephant"];
const removedAnimal = animals.shift();


console.log(animals) // ["tiger", "elephant"]
console.log(removedAnimal) // "lion"
Enter fullscreen mode Exit fullscreen mode

splice() :

  • Allows you to add, remove, or replace elements in an array at a specific index.

  • Modifies the original array and returns an array containing the removed elements (if any).

const color = ["red", "green", "blue"];
colors.splice(1, 1, "yellow"); // remove 1 element at index 1 and insert yellow into it
console.log(colors); // ["red", "yellow", "blue"]
Enter fullscreen mode Exit fullscreen mode

You can read more on splice() MDN

concat() :

  • Creates a new array by combining the elements of one or more arrays.

  • Does not modify the original arrays

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const joinedArray = array1.concat(array2);

console.log(joinedArray); // [1, 2, 3, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

slice() :

  • The slice() method is used to extract a portion of an array and return a new array containing the selected elements.

  • Does not modify the original array

const numbers = [1, 2, 3, 4, 5];
const sliceArray = numbers.slice(1, 4);
console.log(sliceArray); // [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Read more on slice() MDN

Iteration Method

Iteration methods help us to perform repeated specific action or operation on sequence of elements. This methods allow us to perform some certain actions until a condition is met.

We will be discussing some of the most important iteration methods provided by JavaScript.

forEach() :

The forEach method executes a provided function once for each array element. It does not create a new array.

const numbers = [1, 2, 3];
numbers.forEach((number) =>{
    console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

forEach() returns undefined

map() :

The map() method creates a new array with the results of calling a provided function on every element in the array.

const numbers = [1, 2, 3];
const squareNumbers = numbers.map((number) =>{
    return number * number;
})
console.log(squareNumbers) // [1, 4, 9]
Enter fullscreen mode Exit fullscreen mode

filter() :

The filter() method creates a new array with all elements that pass a provided test function.

const words = ["lawyer", "expensive", "freedom", "awesome"];
const filteredWord = words.filter((word) => {
    return word.length <= 7; // return words whose length is less than or equals 7
});

console.log(filteredWord); // ["lawyer", "freedom", "awesome"]
Enter fullscreen mode Exit fullscreen mode

reduce() :

The reduce() method applies a function against an accumulator and each element in the array to reduce it to single value.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) =>{
    return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

some() and every() :

  • some() tests whether at least one element in the array passes the test. Returns a boolean value.

  • every() tests whether all elements in the array pass the test. Returns a boolean value.

const number = [1, 2, 3, 4, 5];
const hasEven = numbers.some((number) =>{
    return number % 2 === 0;
});
console.log(hasEven); // Output: true

const allEven = numbers.every((number) =>{
    return number % 2 === 0;
});
console.log(allEven); // Output: false
Enter fullscreen mode Exit fullscreen mode

All the iteration methods discussed above help you to achieve tasks more elegantly with less boilerplate code. The are also more functional in nature, which aligns with modern programming paradigms.

Multidimensional Array

JavaScript support multidimensional array such as 2D and 3D arrays. Multidimensional array is an array that contains another arrays within it. Multidimensional arrays forms a grid-like structure (matrix) which can be used for data representation. Here is a representation of 2D and 3D array

// 2D Array
const twoDArray = [
    [a, b, c],
    [l, m, n],
    [x, y, z],
];

// 3D Array
consy threeDArray = [
    [
        [u, v, w],
        [i, j, k],
        [e, f, g]
    ],
    [
        [a, b, c],
        [p, q, r],
        [x, y, z]
    ],
]
Enter fullscreen mode Exit fullscreen mode
const multiArray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]; // 2D Array

// Accessing elements in the 2D Array
console.log(multiArray[1, 1]) // 5 (second row, second column)
console.log(multiArray[2, 2]) // 9 (third row, third column)
console.log(multiArray[0, 1]) // 2 (first row, second column)

// Looping through a multidimensional array
for (let i = 0; i < multiArray.length; i++){
    for (let j = 0; j < multiArray[i].length; j++){
       console.log(multiArray[i][j]);
    } // 2D array looping through it twice
} 

/* 
    Output:
    1 2 3 4 5 6 7 8 9
*/
Enter fullscreen mode Exit fullscreen mode

It's important to note that excessively deep nesting can lead to code that is difficult to understand and maintain. It can also have performance implications, as accessing deeply nested elements might become inefficient. In most cases, if you find yourself needing very deep nesting, it might be worth considering alternative data structures or rethinking your data organization to keep your code manageable. For practical purposes, most use case involve array with 2 or 3 level of nesting (2D or 3D arrays).

Using Spread Operator with Arrays

The JavaScript spread operator ... is a versatile syntax introduced in ES6 (ECMAScript 2015) that allows you to expand an iterable into individual elements.

Iterables are objects you can iterates over using the for...of loop syntax

How the spread operator works with Array

  1. Copying Array:

You can use the spread operator to create a shallow copy of an existing array, without modifying the original one.

  const originalArray = [1, 2, 3];
  const copyArray = [...originalArray];
  console.log(copyArray); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
  1. Merging Arrays:

The spread operator can be use to merge multiple arrays into single array.

  const array1 = [1, 2, 3];
  const array2 = [4, 5, 6];
  const mergeArray = [...array1, ...array2];
  console.log(mergeArray) // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode
  1. Passing Function Arguments:

The spread operator can be use to pass elements into a function an individual arguments. Each element in the array is represented an argument in the function.

  function sum(a, b, c){
      return a + b + c;
  }
  const numbers = [1, 2, 3];
  const result = sum(...numbers) // equivalent to sum(1, 2, 3)
  console.log(result) // 6
Enter fullscreen mode Exit fullscreen mode
  1. Adding Element to an Array:

You can add elements to anywhere in an existing array, without modifying the existing array.

  const firstArray = [1, 2, 3];
  const secondArray = [4, 5, 6];
  const addedArray = [...secondArray, ...firstArray]
  console.log(addedArray) // [4, 5, 6, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Summary

In this article we discussed what JavaScript arrays are and how they can be useful. We compared them with regular variable declarations and how they can hold values of different data types.

We covered how array can be created and using both the literal and constructor methods, providing code samples for each method. We discussed how we can access array elements using index numbers and how we can assign new values to array elements using index numbers, with code samples. We also took some time to look into one of the most important array property length, and how it can be used to manipulate arrays and retrieve the length of an array.

We touched on some of the most important JavaScript array methods, such as push, pop, shift, unshift, map . We dig into , among others, with code examples on each method. Later in the article, we delved into how to iterate over array element and how we can perform actions on each array element using the iteration functions. We explored how multidimensional arrays can be useful for data storage, by having arrays inside other arrays.

Lastly, we discuss on how the spread operator can be incredibly useful when working with arrays.

Conclusion

JavaScript developers use JavaScript arrays almost every day in their development process. So understanding the applications and how they can be used can help you in your development work. When working with arrays, it's important to avoid common pitfalls such as accessing elements with wrong index, avoiding infinite loops, and using array methods appropriately for the task at hand.

You can also continue your learning by exploring other array methods that weren't covered in this article or by checking out the MDN documentation for more in-depth information on arrays.

Top comments (0)