Lesson 22: Arrays Part 1

Learn how to create and work with arrays in JavaScript to store and manipulate collections of data.

22.1 Introduction to Arrays in JavaScript

An array is a regular data structure that comprises individual elements that can be referenced using one or more integer index variables. In JavaScript, an array is usually represented using the format arrayName[i], where i is the index or subscript which represents the position of the element within the array. The array always starts with the zeroth element.

Key points: Arrays allow you to store multiple values in a single variable. They are ideal for storing collections of data like lists of items, scores, or any set of related values.

For example, an array A of 8 elements comprises elements A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7].

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]
54 60 23 45 67 90 85 34

From the above table, the value of A[0]=54, A[1]=60, A[2]=23 and so forth.

We can perform arithmetic operations on the array elements. For example:

let x = A[1] + A[2] + A[3]; // Result: 60 + 23 + 45 = 128

22.2 Declaring and Allocating Arrays

In JavaScript, an array can be declared using several methods. If the values of the array are unknown or not initialized at the beginning, we use the following statement:

let A = new Array(12); // Creates an array with 12 elements

The operator new allocates memory to store 12 elements of the array. The process of creating a new object is known as creating an instance of the object, in this case, an Array object.

Different arrays may be created using one single declaration, separated by commas:

let x = new Array(20), 
    y = new Array(15), 
    z = new Array(30);

Example 22.1: Array Initialization and Display

This example shows how to create an array, initialize its values, and display them.

function initArray() {
  let A = new Array(10);
  
  // Initialize array values
  for (let i = 0; i < A.length; i++) {
    A[i] = i * 10;
  }
  
  // Display array values
  let output = "";
  for (let i = 0; i < A.length; i++) {
    output += `element ${i} is ${A[i]}\n`;
  }
  
  document.getElementById("arrayOutput").textContent = output;
}