JavaScript Arrays

Creating Arrays

Arrays are created using square brackets or the Array() constructor.

const fruits = ["apple", "banana", "cherry"];
const numbers = new Array(1, 2, 3, 4);

Accessing Elements

You can access array elements by index (starting from 0):

console.log(fruits[0]);  // "apple"
console.log(fruits[2]);  // "cherry"

Modifying Arrays

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"]

Array Properties and Length

The length property shows the number of items in an array:

console.log(fruits.length);  // e.g., 3

You can also truncate or expand arrays by setting length.

Iterating Through Arrays

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.

Common Methods

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"]);

Best Practices

  • Use const to prevent reassignment of array references
  • Use map, filter, and reduce for cleaner code
  • Avoid using delete on array elements — use splice instead

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic