Skip to content

Arrays

An array is an ordered list that can hold multiple values.
Each element is identified by an index (starting at 0).

Example: ["apple", "banana", "pear"]

  • fruits[0] → “apple”
  • fruits[1] → “banana”

You can create an array using square brackets [].


MethodExampleResult
push()fruits.push("kiwi")Adds to the end
pop()fruits.pop()Removes the last item
shift()fruits.shift()Removes the first item
unshift()fruits.unshift("strawberry")Adds to the beginning
map()fruits.map(f => f.toUpperCase())Transforms the elements
filter()fruits.filter(f => f.startsWith("p"))Filters elements
reduce()[1,2,3].reduce((a,b)=>a+b)Reduces to one value

Loop through using indexes:

for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

Loop directly through values (more readable):

for (let fruit of fruits) {
console.log(fruit);
}

Calls a function on each element:

fruits.forEach(fruit => console.log(fruit));

The map() method creates a new array by applying a function to each element of the original array.

Important: map() does not modify the original array.

Example: transform all items to uppercase.

let fruits = ["apple", "banana", "pear"];
let upper = fruits.map(fruit => fruit.toUpperCase());
console.log(upper); // ["APPLE", "BANANA", "PEAR"]
console.log(fruits); // ["apple", "banana", "pear"] (unchanged)

Another example: extract a property from an array of objects.

let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
let names = users.map(u => u.name);
console.log(names); // ["Alice", "Bob", "Charlie"]

Filter even numbers from an array:

let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

  • Use for...of or forEach for readability.
  • Prefer map, filter, reduce to write more functional and concise code.
  • Avoid mixing different types in the same array (for clarity).