Arrays are versatile data structures that allow developers to store and manipulate multiple values in a single variable. Arrays in JavaScript can hold elements of any data type, making them powerful tools for working with lists, collections, and ordered data.
Creating Arrays
Arrays can be created using square brackets []
, and commas separate elements.
let fruits = ['apple', 'banana', 'orange'];
let numbers = [1, 2, 3, 4, 5];
Accessing Elements
Elements in an array can be accessed using their index. Array indices start at 0.
console.log(fruits[0]); // Output: 'apple'
console.log(numbers[2]); // Output: 3
Modifying Elements
Elements in an array can be modified by assigning new values to their corresponding indices.
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
Array Methods
JavaScript provides a variety of built-in array methods for performing common operations, such as adding, removing, and searching elements.
fruits.push('kiwi'); // Add an element to the end of the array
fruits.pop(); // Remove the last element from the array
fruits.indexOf('orange'); // Find the index of an element