A variable holds ONE value. An ARRAY holds a whole ROW of values β like numbered dragon cages in a line! Index 0 is first, index 1 is second, and so on. Use .push() to rescue a dragon into the last cage, .pop() to release one, and .length to count them all. Arrays power every shopping cart, playlist, and scoreboard in the world!
π What we're MAKING today: My Dragon Array
In Pizza Recipe Machine you wrote a function β a reusable recipe that takes an input and returns a result.
But where do you STORE all those results? In an ARRAY β a single variable that holds many values in a numbered row! π
What is an array? It's a list with numbered slots called indexes. You write
var dragons = ["Ember", "Splash", "Zap"] and each dragon gets a number:
dragons[0] = "Ember", dragons[1] = "Splash", dragons[2] = "Zap".
Counting starts at ZERO β that's the golden rule of arrays!
Add to the end with .push(), remove from the end with .pop(), and check the total with .length.
Every app you've ever used stores lists this way! π
π Last time you wrote function makePizza(topping) and called it with different arguments. Today, instead of baking one pizza at a time, you'll store ALL your results in an array β a row of numbered cages. Push results in, pop them out, count them with .length, and peek at any one with [0], [1], [2]! π
β β β dragon-sanctuary.jsJavaScript
π‘ Tap a purple chip to change the dragon name[ ] = array Β· [0] = first Β· .length = count
sanctuary viewLIVE
π .length
0
π [0] first
empty
π last
empty
π Dragon Cages (array)[ ] Β· length = 0
β¬ push() adds to the END Β· pop() removes the LAST β¬
Step 1 / 5
First Rescue! Push ONE dragon into the empty array. Pick any dragon below, then press π Rescue! (push) to call dragons.push("Ember").
π Which dragon to push() into the array?
π Your 5 Array Challenges
0 of 5 challenges complete
π
You Built the Dragon Array!
You mastered ARRAYS β the most important data structure in programming! You pushed dragons in, popped them out, counted them with .length, and peeked at any one with [0], [1], [2]... Every app you'll ever build uses arrays just like this! πβ¨
π« What You Learned
An array is a numbered list: var dragons = ["Ember", "Splash"] β one variable, many values!
Indexes start at ZERO: dragons[0] is the first, dragons[1] is the second. This is the #1 rule of arrays!
.push(item) adds to the END of the array β like rescuing a dragon into the last cage.
.pop() removes the LAST item β like releasing the most recently rescued dragon.
.length tells you how many items are inside. It grows with each push and shrinks with each pop.
π Your Creation
My Dragon Array
π Come Back Tomorrow!
Next up: FOR LOOPS β what if you need to visit EVERY dragon in your array, one by one? A loop lets you repeat code automatically: for (var i = 0; i < dragons.length; i++) visits every cage! Turn your static array into a living sanctuary that feeds, counts, and plays with every dragon! π