Skip to content

Understanding Arrays in JavaScript

Arrays are a fundamental part of modern JavaScript, allowing developers to store and manipulate lists of data efficiently. Whether you’re building simple applications or working on larger projects, understanding arrays is key to working with data effectively.

In this article, we’ll cover:

  • How to create arrays.
  • Accessing and modifying elements.
  • Common array methods.
  • Looping through arrays.

Let’s dive in!


There are two common ways to create arrays in JavaScript:

  1. Using square brackets ([]):

This is the most common and recommended method:

const fruits = ["apple", "banana", "cherry"];
  1. Using the new Array() constructor:

This method is less commonly used but valid:

const numbers = new Array(1, 2, 3, 4);

Both methods create an array you can manipulate later.


You can access or modify an array element using its index. Remember, arrays in JavaScript are zero-indexed, so the first element is at index 0.

Accessing elements:

const colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: "red"

Modifying elements:

colors[1] = "yellow";
console.log(colors); // Output: ["red", "yellow", "blue"]

Here are some commonly used array methods to add, remove, or manipulate elements:

  • push: Adds an element to the end of the array.
  • pop: Removes the last element of the array.
  • shift: Removes the first element of the array.
  • unshift: Adds an element to the start of the array.

Example:

const numbers = [1, 2, 3];
numbers.push(4); // Adds 4 to the end numbers.pop(); // Removes the last element (4)
numbers.unshift(0); // Adds 0 to the start numbers.shift(); // Removes the first element (0)
console.log(numbers); // Output: [1, 2, 3]
  • splice: Adds or removes elements at a specific index.
  • slice: Returns a shallow copy of a portion of the array.
  • indexOf: Finds the first occurrence of a value in the array.

Examples:

const animals = ["dog", "cat", "rabbit"];
// Splice: Modifying the array
animals.splice(1, 0, "hamster"); // Adds "hamster" at index 1
console.log(animals); // Output: ["dog", "hamster", "cat", "rabbit"]
// Slice: Creating a new array
const firstTwo = animals.slice(0, 2);
console.log(firstTwo); // Output: ["dog", "hamster"]
// IndexOf: Finding the position
const index = animals.indexOf("rabbit");
console.log(index); // Output: 3

Iterating over arrays is a common task in JavaScript. Here are different ways to loop through arrays:

The classic for loop gives complete control:

const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

More concise and perfect for iterating over array values:

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

A modern and functional approach to iterating arrays:

fruits.forEach((fruit) => {
console.log(fruit);
});