javascript · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every item in an array has an , starting at 0.
Picture a queue at an ice cream van. JavaScript numbers each place in the queue, starting at 0, not 1. That number is the index, so queue[0] is the person at the front.
The last index is one less than the length, so queue[queue.length - 1] is the back of the queue. Ask for a place nobody is in and you get , meaning no value.
To swap someone, use = with an index: queue[1] = "Dev"; puts Dev in place 1. To add someone, them: queue.push("Eli"); puts Eli on the end.
let queue = ["Ava", "Ben", "Cleo"];
console.log(queue[0], queue[queue.length - 1]);
queue[1] = "Dev";
queue.push("Eli");
console.log(queue); Use square brackets to read an item and round brackets for a method like .push().
guess first
Which planet is at index 1?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let planets = ["Mercury", "Venus", "Earth"];
console.log(planets[1]);
your turn
Your turn. Pick the team.
Swap the player at the front for someone new, then push one more player on the end. Type a name in each blank and press run.
fix it
You asked for the last cake and got undefined. Fix it!
- There are three cakes. If the index starts at 0, what is the last index?
- The indexes are 0, 1 and 2. Index 3 is an empty place, so you get
undefined. - Change 3 to 2, or to cakes.length - 1, then press run.
nailed it
you can pick out any item now. :D
- The index starts at 0, so the first item is
[0]. - The last item is at
.length - 1. .push()adds an item to the end of an array.
new words in your collection
- index
- push
- undefined
This lesson isn’t saved. A free account remembers every lesson you finish.