Lesson 5 - Lists
Lists in JavaScript
Array is a collection that can store multiple values in a single variable.
let fruits = ["apple", "banana"];
console.log(fruits);
let numbers = [10, 20, 30];
console.log(numbers[0]);
let colors = ["red", "blue"];
colors[1] = "green";
console.log(colors);
You can add, remove or change items inside an array.
💡 sort() puts the array items in order (alphabetical for words; for numbers, add a compare function, otherwise it sorts them as text!).
let animals = ["cat", "dog"];
animals.push("elephant");
console.log(animals);
let pets = ["dog", "cat"];
pets = pets.filter(p => p !== "cat");
console.log(pets);
let letters = ["a", "c", "b"];
letters.sort();
console.log(letters);
Looping and slicing help you work with multiple array items at once.
let friends = ["Lina", "Max"];
for (let f of friends) {
console.log("Hello", f);
}
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(1, 4));
let a = [1, 2];
let b = [3, 4];
let c = [...a, ...b];
console.log(c);
💡 .length tells you how many items are in an array — very useful when looping!
let toys = ["ball", "kite", "robot"];
console.log(toys.length);
let days = ["Mon", "Tue", "Wed"];
console.log(days.indexOf("Tue"));
Make an Array
console.log(fruits);
🎯 Add your own fruit.
Access by Index
console.log(numbers[0]);
console.log(numbers[2]);
💡 Remember: counting starts at 0.
Change an Item
colors[1] = "yellow";
console.log(colors);
🎯 Try changing another color.
Add to an Array
animals.push("elephant");
console.log(animals);
💡 push() adds to the end.
Remove from an Array
pets = pets.filter(p => p !== "cat");
console.log(pets);
🎯 Try removing something else.
Array Length
console.log(letters.length);
💡 How many items are there?
Slicing an Array
console.log(numbers.slice(1, 4));
🎯 Which numbers do you see?
Loop Through an Array
for (let f of friends) {
console.log("Hello", f);
}
💡 Add your name and run again.
Sort an Array
scores.sort((a, b) => a - b);
console.log(scores);
🎯 Try removing "(a, b) => a - b" — what changes?
Mix Arrays
let b = [3, 4];
let c = [...a, ...b];
console.log(c);
💡 What happens if you do [...b, ...a]?