Lesson 5 - Lists

Lists in JavaScript

Array is a collection that can store multiple values in a single variable.

// Example of an array
let fruits = ["apple", "banana"];
console.log(fruits);
// Access by index
let numbers = [10, 20, 30];
console.log(numbers[0]);
// Change an item
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!).

// Add an item (to the end)
let animals = ["cat", "dog"];
animals.push("elephant");
console.log(animals);
// Remove an item (by value)
let pets = ["dog", "cat"];
pets = pets.filter(p => p !== "cat");
console.log(pets);
// Sort array
let letters = ["a", "c", "b"];
letters.sort();
console.log(letters);

Looping and slicing help you work with multiple array items at once.

// Loop through an array
let friends = ["Lina", "Max"];
for (let f of friends) {
  console.log("Hello", f);
}
// Slice an array
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(1, 4));
// Combine arrays
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!

// Count items
let toys = ["ball", "kite", "robot"];
console.log(toys.length);
// Find an item's position
let days = ["Mon", "Tue", "Wed"];
console.log(days.indexOf("Tue"));

Make an Array

let fruits = ["apple", "banana", "cherry"];
console.log(fruits);

🎯 Add your own fruit.


Access by Index

let numbers = [10, 20, 30];
console.log(numbers[0]);
console.log(numbers[2]);

💡 Remember: counting starts at 0.


Change an Item

let colors = ["red", "blue", "green"];
colors[1] = "yellow";
console.log(colors);

🎯 Try changing another color.


Add to an Array

let animals = ["cat", "dog"];
animals.push("elephant");
console.log(animals);

💡 push() adds to the end.


Remove from an Array

let pets = ["dog", "cat", "hamster"];
pets = pets.filter(p => p !== "cat");
console.log(pets);

🎯 Try removing something else.


Array Length

let letters = ["a", "b", "c", "d"];
console.log(letters.length);

💡 How many items are there?


Slicing an Array

let numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(1, 4));

🎯 Which numbers do you see?


Loop Through an Array

let friends = ["Lina", "Max", "Zara"];
for (let f of friends) {
  console.log("Hello", f);
}

💡 Add your name and run again.


Sort an Array

let scores = [40, 10, 30, 20];
scores.sort((a, b) => a - b);
console.log(scores);

🎯 Try removing "(a, b) => a - b" — what changes?


Mix Arrays

let a = [1, 2];
let b = [3, 4];
let c = [...a, ...b];
console.log(c);

💡 What happens if you do [...b, ...a]?

Back Next Lesson