Arrays

Introduction

In JavaScript, an array is a special variable that can hold more than one value at a time. Arrays are widely used to store collections of data, such as lists of items or sets of related values. They are versatile and can be manipulated in various ways to perform operations like adding, removing, or modifying elements.

This documentation aims to provide a comprehensive overview of arrays in JavaScript, covering their creation, manipulation, and common methods.

Table of Contents

  1. Creating Arrays

  2. Accessing Array Elements

  3. Modifying Arrays

  4. Common Array Methods

1. Creating Arrays

Arrays in JavaScript can be created using array literals or the Array constructor.

Array Literals

// Creating an empty array
let emptyArray = [];

// Creating an array with initial values
let colors = ['red', 'green', 'blue'];

Array Constructor

2. Accessing Array Elements

Array elements can be accessed using square brackets [] notation along with the index of the element. Remember, in JavaScript, arrays are zero-indexed.

3. Modifying Arrays

Arrays in JavaScript are mutable, meaning their elements can be changed, added, or removed after creation.

Adding Elements

Removing Elements

4. Common Array Methods

JavaScript provides a variety of built-in methods to manipulate arrays efficiently.

push()

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

pop()

Removes the last element from an array and returns that element.

forEach()

Executes a provided function once for each array element.

This documentation covers the basic operations and methods of arrays in JavaScript. Arrays are fundamental data structures in JavaScript, and understanding how to work with them is essential for any JavaScript developer.