Arrays are created using square brackets or the Array() constructor.
const fruits = ["apple", "banana", "cherry"];
const numbers = new Array(1, 2, 3, 4);You can access array elements by index (starting from 0):
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"Use index assignments and array methods to modify contents:
fruits[1] = "blueberry"; // ["apple", "blueberry", "cherry"]
fruits.push("date"); // ["apple", "blueberry", "cherry", "date"]
fruits.pop(); // ["apple", "blueberry", "cherry"]
fruits.unshift("avocado"); // ["avocado", "apple", "blueberry", "cherry"]
fruits.shift(); // ["apple", "blueberry", "cherry"]
fruits.splice(1, 0, "kiwi"); // ["apple", "kiwi", "blueberry", "cherry"]The length property shows the number of items in an array:
console.log(fruits.length); // e.g., 3You can also truncate or expand arrays by setting length.
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
for (let fruit of fruits) {
console.log(fruit);
}
fruits.forEach((fruit) => console.log(fruit));Use for...of for clean iteration, and forEach when applying a function to each element.
JavaScript arrays include powerful methods:
const doubled = numbers.map(x => x * 2);
const even = numbers.filter(x => x % 2 === 0);
const sum = numbers.reduce((total, num) => total + num, 0);
const sliced = fruits.slice(1, 3);
const sorted = fruits.sort();
const combined = fruits.concat(["grape", "melon"]);const to prevent reassignment of array referencesmap, filter, and reduce for cleaner codesplice insteadAsk the AI if you need help understanding or want to dive deeper in any topic