Arrays are fundamental data structures in JavaScript. They allow you to store multiple values in a single variable, making it easier to manage and manipulate collections of data.
There are two common ways to create arrays in JavaScript:
const fruits = ['apple', 'banana', 'orange'];
const numbers = new Array(1, 2, 3, 4, 5);
Array elements are accessed using zero-based indexing. The first element is at index 0, the second at index 1, and so on.
const colors = ['red', 'green', 'blue'];
console.log(colors[0]); // Output: 'red'
console.log(colors[2]); // Output: 'blue'
JavaScript arrays come with built-in properties and methods that make working with them efficient and convenient.
length
: Returns the number of elements in an array.push()
: Adds one or more elements to the end of an array.pop()
: Removes the last element from an array.unshift()
: Adds one or more elements to the beginning of an array.shift()
: Removes the first element from an array.slice()
: Returns a shallow copy of a portion of an array.splice()
: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.JavaScript provides several ways to iterate over arrays. Here are two common methods:
const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
console.log(fruit);
}
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));
For more advanced array operations, you might want to explore JavaScript Array Methods and JavaScript Array Iteration techniques.
JavaScript supports multi-dimensional arrays, which are arrays of arrays. These are useful for representing grids or matrices.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][1]); // Output: 5
Arrays are versatile and powerful. They form the backbone of many JavaScript operations and data structures. As you progress in your JavaScript journey, you'll find arrays indispensable for managing collections of data effectively.
To deepen your understanding of JavaScript arrays and related topics, explore these concepts: