Introduction to Arrays in JavaScript

4/16/2025

Looping through an array using for loop and forEach in JavaScript

Go Back

Introduction to Arrays in JavaScript

Arrays are one of the most commonly used data structures in JavaScript. They allow you to store multiple values in a single variable, making it easy to organize and manipulate collections of data.

In this tutorial, we'll cover the basics of arrays, how to create them, access elements, and use common methods.


 Looping through an array using for loop and forEach in JavaScript

What is an Array?

An array is a special variable that can hold more than one value at a time. Values in an array are ordered and indexed starting from 0.

Example:

const fruits = ["apple", "banana", "cherry"];
  • fruits[0] returns "apple"

  • fruits[1] returns "banana"


Creating Arrays

You can create arrays in two main ways:

1. Using Array Literals (Recommended)

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

2. Using the Array Constructor

const cars = new Array("Toyota", "BMW", "Tesla");

Accessing Array Elements

You access an array element by referring to its index:

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

Modifying Array Elements

colors[0] = "yellow"; // Changes "red" to "yellow"

Array Length

The length property returns the number of elements in an array:

console.log(colors.length); // Output: 3

Common Array Methods

Here are some useful built-in methods to work with arrays:

1. push() - Adds element to the end

colors.push("purple");

2. pop() - Removes the last element

colors.pop();

3. shift() - Removes the first element

colors.shift();

4. unshift() - Adds element to the beginning

colors.unshift("pink");

5. indexOf() - Finds the index of an element

colors.indexOf("blue");

6. includes() - Checks if value exists

colors.includes("green");

Looping Through Arrays

You can loop through arrays using:

for loop:

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

forEach() method:

fruits.forEach(function(item) {
  console.log(item);
});

Final Thoughts

Arrays are a fundamental concept in JavaScript. They help manage and process lists of data efficiently. As you grow in your JavaScript journey, mastering arrays will allow you to build more dynamic and powerful web applications.

In the next tutorials, we’ll dive into array methods like map, filter, reduce, and how to work with multi-dimensional arrays.

Table of content