JavaScript — Lesson 6
Arrays & Loops
Working with collections of data.
Arrays & Loops
Arrays store collections of data, and loops let you work with each item in the collection.
Creating Arrays
// Literal syntax (recommended)
const fruits = ["apple", "banana", "orange"];
// Mixed types
const mixed = [1, "hello", true, { name: "Alice" }];
Accessing Array Items
fruits[0]; // "apple" (first item, index 0)
fruits[1]; // "banana"
fruits[2]; // "orange"
fruits.length; // 3
fruits[fruits.length - 1]; // "orange" (last item)
Array Methods
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4] (add to end)
arr.pop(); // [1, 2, 3] (remove from end)
arr.unshift(0); // [0, 1, 2, 3] (add to start)
arr.shift(); // [1, 2, 3] (remove from start)
arr.indexOf(2); // 1 (find index)
arr.includes(3); // true (check if exists)
arr.join(", "); // "1, 2, 3" (convert to string)
For Loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// "apple"
// "banana"
// "orange"
For...of Loop (ES6)
Simpler syntax for iterating over arrays.
for (const fruit of fruits) {
console.log(fruit);
}
Array Methods: forEach, map, filter
// forEach: do something with each item
fruits.forEach(fruit => {
console.log("I like " + fruit);
});
// map: create a new array by transforming each item
const uppercased = fruits.map(f => f.toUpperCase());
// ["APPLE", "BANANA", "ORANGE"]
// filter: create a new array with items that pass a test
const longNames = fruits.filter(f => f.length > 5);
// ["banana", "orange"]
While Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Tip: Prefer
for...of for simple iteration and map/filter/forEach for more specific transformations.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →