JavaScript arrays are versatile data structures used to store multiple values in a single variable. Arrays can hold elements of any data type, including strings, numbers, objects, and even other arrays. Here's an overview of working with arrays in JavaScript:
You can create an array using array literals, which are enclosed in square brackets [], and separate elements with commas.
let fruits = ['apple', 'banana', 'orange'];
let numbers = [1, 2, 3, 4, 5];
You can access individual elements of an array using square bracket notation with the index of the element. Note that array indices start from 0.
console.log(fruits[0]); // Output: 'apple'
console.log(numbers[2]); // Output: 3
You can modify elements of an array by assigning new values to specific indices.
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
You can determine the number of elements in an array using the length property.
console.log(fruits.length); // Output: 3
You can add elements to the end of an array using the push() method or to the beginning using the unshift() method.
fruits.push('kiwi');
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'kiwi']
You can remove elements from the end of an array using the pop() method or from the beginning using the shift() method.
fruits.pop();
console.log(fruits); // Output: ['apple', 'grape', 'orange']
You can loop through the elements of an array using for loops or array methods like forEach() , map() , filter() , etc.
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output:
// 'apple'
// 'grape'
// 'orange'
JavaScript allows you to create arrays of arrays, forming multidimensional arrays.
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(matrix[1][2]); // Output: 6
Arrays are fundamental data structures in JavaScript, providing a flexible way to organize and manipulate collections of data. By understanding how to create, access, modify, and iterate over arrays, you can effectively work with complex data structures in your JavaScript programs. Arrays are extensively used in various programming tasks, including data processing, algorithms, and user interface development.