Arrays: Super Lists! ๐โจ
Keep track of LOTS of things at once - like a shopping list, your favorite games, or your friend's names!
๐ค What is an Array?
An array is a special list that can hold many things together in order. Think of it like a row of lockers, each with a number!
๐ฌ My Favorite Candies
Each item has a number (starting from 0!)
๐ Arrays in Real Life
You see arrays everywhere!
Shopping List
Milk, eggs, bread, apples...
Music Playlist
Song 1, Song 2, Song 3...
Class List
All the students in your class!
Lockers
Locker 1, Locker 2, Locker 3...
Days of Week
Mon, Tue, Wed, Thu, Fri...
High Scores
1st place, 2nd place, 3rd place...
โจ Making an Array
Use square brackets [ ] to make an array:
// A list of fruits
let fruits = [ "apple" , "banana" , "orange" ] // A list of numbers
let scores = [ 100 , 85 , 92 , 78 ] ๐คฏ Fun Fact: Counting Starts at 0!
In programming, we start counting from ZERO, not one! It's a bit weird at first, but you'll get used to it!
First!
Second!
Third!
Fourth!
๐ฏ Getting Items from an Array
Use the item's number (index) to get it:
let pets = [ "dog" , "cat" , "fish" , "bird" ] pets[0] โ "dog" ๐ pets[2] โ "fish" ๐ ๐ Changing Items in an Array
You can change any item by using its number:
Before:
colors = ["red", "blue"] After: colors[1] = "green"
colors = ["red", "green"] โ Adding Items to an Array
Use push() to add new items at the end:
Start with:
fruits.push("orange") Now you have:
๐ฎ Arrays in Games!
Video games use arrays ALL the time!
Inventory
Array of all items you've collected!
Leaderboard
Array of player scores, sorted highest first!
Enemies
Array of all the bad guys on screen!
Level Map
Arrays of arrays make a whole world!
๐ How Many Items? Array Length!
Use .length to count items:
let friends = [ "Emma" , "Liam" , "Sophia" ]
friends. length // This is 3! โญ Remember This!
- 1
Arrays are lists that hold many things together
- 2
Use square brackets [ ] to make an array
- 3
Counting starts at ZERO (0), not one!
- 4
Use .push() to add new items to the end