JavaScript Arrays: A Comprehensive Guide

Java Script @ Freshers.in

An array in JavaScript is a single variable that can store multiple values. Each value inside an array is identified by an index, starting at 0.

Example:

let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // Outputs: apple

Key JavaScript Array Methods

push() & pop()

The push() method adds one or more elements to the end of an array, while pop() removes the last element.

Example:

let colors = ['red', 'blue'];
colors.push('green');
console.log(colors); // Outputs: ['red', 'blue', 'green']
colors.pop();
console.log(colors); // Outputs: ['red', 'blue']
shift() & unshift()

While pop() and push() act on the end of an array, shift() removes the first element, and unshift() adds elements to the beginning.

Example:

let animals = ['cat', 'dog'];
animals.unshift('elephant');
console.log(animals); // Outputs: ['elephant', 'cat', 'dog']
animals.shift();
console.log(animals); // Outputs: ['cat', 'dog']
join()

This method combines all the elements of an array into a single string, separated by a specified delimiter.

Example:

let names = ['Alice', 'Bob', 'Charlie'];
console.log(names.join(', ')); // Outputs: Alice, Bob, Charlie
slice()

slice() returns a shallow copy of a portion of an array into a new array.

Example:

let numbers = [1, 2, 3, 4, 5];
let subset = numbers.slice(1, 4);
console.log(subset); // Outputs: [2, 3, 4]

splice()

This method can change the contents of an array by removing, replacing, or adding elements.

Example:

let items = ['a', 'b', 'c', 'd'];
items.splice(1, 2, 'x', 'y');
console.log(items); // Outputs: ['a', 'x', 'y', 'd']

forEach()

It’s an efficient way to loop through an array’s elements.

Example:

let scores = [90, 85, 78, 92];
scores.forEach(score => console.log(score));

Multidimensional Arrays

JavaScript supports arrays of arrays, known as multidimensional arrays. These arrays can be visualized as tables (or matrices) with rows and columns.

Example:

let matrix = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
console.log(matrix[1][2]); // Outputs: 6
Author: user