In JavaScript, an array is a data structure that allows you to store a collection of values in a single variable. These values can be of any data type (numbers, strings, objects, other arrays, etc.). Arrays are commonly used to hold lists of items or related data that can be accessed by their index.
You can create an array in two main ways:
Using square brackets []
(most common):
let fruits = ["apple", "banana", "orange"];
Using the Array
constructor:
let numbers = new Array(1, 2, 3, 4);
Array elements are accessed using their index, which starts from 0
.
console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"
You can modify an element by assigning a new value to it using its index.
fruits[1] = "mango";
console.log(fruits); // Output: ["apple", "mango", "orange"]
JavaScript arrays come with several properties and methods for easy manipulation:
In JavaScript, arrays have numerous built-in methods to handle and manipulate data. Here's a breakdown of some of the most commonly used array methods with examples:
push()
Adds one or more elements to the end of an array and returns the new length.
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]
pop()
Removes the last element from an array and returns that element.