An array in JavaScript is a special variable that can store multiple values in a single container. Arrays can hold numbers, strings, objects, or even other arrays.
const fruits = ["apple", "banana", "orange"];
const numbers = [1, 2, 3, 4, 5];
Array items are accessed using their index (starting from 0
).
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: orange
push()
– Adds an item to the endpop()
– Removes the last itemshift()
– Removes the first itemunshift()
– Adds an item to the beginninglength
– Returns the number of elementsincludes()
– Checks if an item existsindexOf()
– Returns the index of an itemforEach()
– Runs a function on each elementconst colors = ["red", "green", "blue"];
colors.push("yellow"); // Adds 'yellow'
console.log(colors.length); // Output: 4
colors.forEach(function(color) {
console.log(color);
});
Arrays are useful for storing lists of items and looping through them efficiently. JavaScript also supports advanced methods like map()
, filter()
, and reduce()
for powerful data manipulation.
Creating arrays using literals or the Array constructor.
let fruits = ["apple", "banana", "cherry"]; console.log(fruits); // Output: ["apple", "banana", "cherry"]
Different array methods for manipulating arrays.
let numbers = [1, 2, 3]; numbers.push(4); console.log(numbers); // Output: [1, 2, 3, 4]
Creating and accessing elements in a 2D array.
let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(matrix[0]); // Output: [1, 2, 3] console.log(matrix[1][2]); // Output: 6