Codeskill

Learn to code, step by step

JavaScript Arrays: Handling Multiple Values Efficiently

JavaScript arrays – how to store, access, and manipulate multiple values in a single variable.

What is an array?

An array is one variable that holds a list of values. It can contain numbers, strings, objects, or other arrays.

Creating an array

The usual way is square brackets []:

Example

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);  // Outputs: ["Apple", "Banana", "Cherry"]

You can also use new Array(), but the bracket syntax is more common.

Accessing elements

Array indices start at zero. Use the index in square brackets to read a value.

Example

let firstFruit = fruits[0];  // Apple
console.log(firstFruit);

Array length

The length property tells you how many elements an array holds.

Example

console.log(fruits.length);  // Outputs: 3

Modifying arrays

You can add, remove, or change elements after creation.

Adding elements

push() adds an element to the end.

Example

fruits.push("Orange");
console.log(fruits);  // Outputs: ["Apple", "Banana", "Cherry", "Orange"]

Removing elements

pop() removes the last element.

Example

fruits.pop();
console.log(fruits);  // Outputs: ["Apple", "Banana", "Cherry"]

Looping through an array

A for loop is the straightforward way to process each element.

Example

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

Array methods

JavaScript includes built-in methods for common array tasks: map(), filter(), reduce(), and others.

The map() method

map() creates a new array by running a function on every element.

Example

let lengths = fruits.map(fruit => fruit.length);
console.log(lengths);  // Outputs: [5, 6, 6]

The filter() method

filter() returns a new array containing only elements that pass a test.

Example

let longFruits = fruits.filter(fruit => fruit.length > 5);
console.log(longFruits);  // Outputs: ["Banana", "Cherry"]

The reduce() method

reduce() runs a function on each element and collapses the result into a single value.

Example

let sum = [1, 2, 3, 4, 5].reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum);  // Outputs: 15

Multidimensional arrays

Arrays can contain other arrays – useful for grids and matrices.

Example

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[1][2]);  // Outputs: 6 (second row, third column)

Arrays are one of the most used structures in JavaScript. Try creating a few, modifying them, and running map() and filter() before moving on to objects.

PreviousLooping the Loop: Understanding For, While, and Do-While Loops