Arrays
What is an array?
Section titled “What is an array?”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”
Creating an array
Section titled “Creating an array”You can create an array using square brackets []
.
Main methods
Section titled “Main methods”Method | Example | Result |
---|---|---|
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 |
Iterating over an array
Section titled “Iterating over an array”With a classic for
Section titled “With a classic for”Loop through using indexes:
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}
With for...of
Section titled “With for...of”Loop directly through values (more readable):
for (let fruit of fruits) { console.log(fruit);}
With forEach
Section titled “With forEach”Calls a function on each element:
fruits.forEach(fruit => console.log(fruit));
Focus: the map()
method
Section titled “Focus: the map() method”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"]
Practical example
Section titled “Practical example”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]
Best practices
Section titled “Best practices”- Use
for...of
orforEach
for readability. - Prefer
map
,filter
,reduce
to write more functional and concise code. - Avoid mixing different types in the same array (for clarity).