What are Arrays?
An array is a collection of elements (values) stored in a single variable. Each element in an array can be accessed by its index (position), starting from 0.
Think of an array like a row of boxes, each containing a value:
- Box 0 contains the first element
- Box 1 contains the second element
- Box 2 contains the third element
- And so onโฆ
Why Use Arrays?
- Store multiple values in one variable
- Easy to access values by position
- Useful for loops (process many items at once)
- Organize related data together
Code Runner Challenge
Add or remove a new value in the array and see what happens!
View IPYNB Source
%%js
// CODE_RUNNER: Add or remove a new value in the array and see what happens!
let fruits = ["apple", "banana", "orange", "grape"];
console.log("My array of fruits:");
console.log(fruits);
console.log();
console.log("First fruit (index 0):", fruits[0]);
console.log("Third fruit (index 2):", fruits[2]);
console.log();
console.log("Number of fruits:", fruits.length);
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Modifying Arrays
You can change, add, or remove elements from an array:
Code Runner Challenge
Practice modifying arrays by changing, adding, and removing elements!
View IPYNB Source
%%js
// CODE_RUNNER: Practice modifying arrays by changing, adding, and removing elements!
// Start with an array
let colors = ["red", "blue", "green"];
console.log(colors);
console.log();
// Change an element
colors[1] = "yellow";
console.log(colors);
console.log();
// Add an element
colors.push("purple");
console.log(colors);
console.log();
// Remove an element
colors.splice(colors.indexOf("red"), 1);
console.log(colors);
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Looping Through Arrays
Arrays are powerful when combined with loops. You can process each element without writing it by hand:
Code Runner Challenge
Modify the numbers array to see different outputs
View IPYNB Source
%%js
// CODE_RUNNER: Modify the numbers array to see different outputs
// Using a for loop to go through each element
let numbers = [10, 20, 30, 40, 50];
console.log("Numbers in the array:");
for (let num of numbers) {
console.log(num);
}
console.log();
console.log("Double each number:");
for (let num of numbers) {
console.log(num * 2);
}
console.log();
console.log("Using index to access elements:");
for (let i = 0; i < numbers.length; i++) {
// conversion fails with template literals
console.log(`Index ${i}: ${numbers[i]}`);
// conversion works with concat
console.log("Index " + i + ": " + numbers[i] );
}
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Real-World Example: Student Grades
Letโs calculate the average grade of students:
Code Runner Challenge
Change the student grades to yours in the array to see different results
View IPYNB Source
%%js
// CODE_RUNNER: Change the student grades to yours in the array to see different results
// Array of student grades
let grades = [85, 92, 78, 95, 88, 91];
// Calculate the sum
let total = 0;
for (let grade of grades) {
total = total + grade;
}
// Calculate the average
let average = total / grades.length;
console.log(`Student grades: ${grades}`);
console.log(`Total points: ${total}`);
console.log(`Number of students: ${grades.length}`);
console.log(`Average grade: ${average.toFixed(1)}`);
console.log();
// Find the highest and lowest grades
console.log(`Highest grade: ${Math.max(...grades)}`);
console.log(`Lowest grade: ${Math.min(...grades)}`);
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
Key Takeaways
โ
Arrays store multiple values in a single variable
โ
Index starts at 0 for the first element
โ
Access elements using array[index]
โ
Use loops to process all elements
โ
Common operations: append, remove, change, loop, sum, average
Arrays are one of the most important data structures in programming. Master them and youโll be able to solve many problems efficiently!
Arrays Homework ๐ฏ
Welcome to the Arrays homework! These exercises will help you practice the key array concepts from the lesson: accessing elements, modifying arrays, looping through arrays, and performing calculations.
Complete all exercises below. Good luck! ๐ช
Exercise 1: Array Basics - Access Elements
Create an array with 5 different items (could be favorite movies, books, games, etc.). Then:
- Print the entire array
- Access and print the first element (index 0)
- Access and print the last element
- Print the total number of items in the array
%%js
const favoriteMovies = ["Inception", "The Matrix", "Interstellar", "The Shawshank Redemption", "Pulp Fiction"];
console.log("Entire array:", favoriteMovies);
console.log("First element:", favoriteMovies[0]);
console.log("Last element:", favoriteMovies[favoriteMovies.length - 1]);
console.log("Total number of items:", favoriteMovies.length);
Exercise 2: Modify Arrays
Start with this shopping list: ["milk", "eggs", "bread", "cheese"]
Then perform these operations:
- Print the original array
- Change the second item to โbutterโ
- Add โyogurtโ to the end using push()
- Remove โbreadโ from the array
- Print the final array
%%js
let shoppingList = ["milk", "eggs", "bread", "cheese"];
console.log("Original array:", shoppingList);
shoppingList[1] = "butter";
shoppingList.push("yogurt");
const breadIndex = shoppingList.indexOf("bread");
shoppingList.splice(breadIndex, 1);
console.log("Final array:", shoppingList);
Exercise 3: Loop Through an Array
Create an array with 5 numbers: [10, 25, 30, 15, 20]
Write a loop that:
- Prints each number with a message (e.g., โNumber: 10โ)
- Prints each number multiplied by 2
- Calculates and prints the sum of all numbers
%%js
const numbers = [10, 25, 30, 15, 20];
console.log("1. Printing each number:");
for (let i = 0; i < numbers.length; i++) {
console.log("Number: " + numbers[i]);
}
console.log("\n2. Each number multiplied by 2:");
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i] * 2);
}
console.log("\n3. Sum of all numbers:");
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Total sum: " + sum);
Google form link is here: https://forms.gle/X47CB92yKuLVRHq98