Arrays
Learn about arrays in JavaScript, including how to create, access, and manipulate them.
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: 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);
Modifying Arrays
You can change, add, or remove elements from an array:
// 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);
Looping Through Arrays
Arrays are powerful when combined with loops. You can process each element without writing it by hand:
// 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] );
}
Real-World Example: Student Grades
Let’s calculate the average grade of students:
// 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)}`);
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
// CODE_RUNNER: Exercise 1 - Array Basics
// Create an array with 5 favorite movies
let favoriteMovies = ["The Shawshank Redemption", "Inception", "The Dark Knight", "Pulp Fiction", "Forrest Gump"];
// 1. Print the entire array
console.log("Entire array:", favoriteMovies);
// 2. Access and print the first element (index 0)
console.log("First element:", favoriteMovies[0]);
// 3. Access and print the last element
console.log("Last element:", favoriteMovies[favoriteMovies.length - 1]);
// 4. Print the total number of items in the array
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
// CODE_RUNNER: Exercise 2 - Arrays Manipulation
// Start with the shopping list
let shoppingList = ["milk", "eggs", "bread", "cheese"];
// 1. Print the original array
console.log("Original array:", shoppingList);
// 2. Change the second item (index 1) to "butter"
shoppingList[1] = "butter";
// 3. Add "yogurt" to the end using push()
shoppingList.push("yogurt");
// 4. Remove "bread" from the array (use splice to find and remove it)
let breadIndex = shoppingList.indexOf("bread");
if (breadIndex > -1) {
shoppingList.splice(breadIndex, 1);
}
// 5. Print the final array
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
// CODE_RUNNER: Exercise 3 - Loop Through an Array
// Create an array with 5 numbers
let numbers = [10, 25, 30, 15, 20];
// 1. Print each number with a message
console.log("--- Each number with a message ---");
for (let i = 0; i < numbers.length; i++) {
console.log("Number: " + numbers[i]);
}
// 2. Print each number multiplied by 2
console.log("--- Each number multiplied by 2 ---");
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i] + " * 2 = " + (numbers[i] * 2));
}
// 3. Calculate and print the sum of all numbers
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log("Sum of all numbers: " + sum);
Google form link is here: https://forms.gle/X47CB92yKuLVRHq98