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

// Using the Array constructor
let numbers = new Array();
let fruits = new Array('apple', 'banana', 'orange');

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.

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

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

3. Modifying Arrays

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

Adding Elements

let fruits = ['apple', 'banana'];

// Adding elements to the end of the array
fruits.push('orange');

Removing Elements

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

// Removing the last element
fruits.pop();

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.

let fruits = ['apple', 'banana'];
fruits.push('orange');
// fruits is now ['apple', 'banana', 'orange']

pop()

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

let fruits = ['apple', 'banana', 'orange'];
let removedFruit = fruits.pop();
// removedFruit is 'orange', fruits is now ['apple', 'banana']

forEach()

Executes a provided function once for each array element.

let numbers = [1, 2, 3];
numbers.forEach(function(num) {
  console.log(num);
});
// Output:
// 1
// 2
// 3

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.

Last updated