Arrays · Lesson 19 of 45
Array basics
A list of values: add, remove and loop over it.
An array is an ordered list in [ ]. Each item has a number (index) starting at 0, and items can be any type, even other arrays.
langs =
langs[2] is "JS" and langs.length is 3. The last item is always langs[langs.length - 1].
| Method | What it does |
|---|---|
| adds to the end |
| removes and returns the last item |
| adds to the start |
| removes the first item |
| is it there? |
| its index (or -1) |
| a copy of a part |
| removes n items at i (changes the original) |
| turns it into text |
- ▶const cart = ["pen"]
- 2cart.push("book")
- 3cart.unshift("bag")
- 4const last = cart.pop()
- 5console.log(cart, last)
Variables
| cart | ["pen"] |
Output
const langs = ["HTML", "CSS", "JS"]
for (const lang of langs) {
console.log("I learn", lang)
}
langs.forEach((lang, i) => console.log(i, lang))
console.log(langs.join(" + "))What's the output?
const a = [3, 6, 9] console.log(a[1]) console.log(a.length)
What will this code print?
Complete the code
Add "Go" to the end and remove the first item.
const langs = ["C", "Java"] langs.("Go") langs.()
Exercise
Print the last item ("Python") without writing its index.
Expected output: Python
const langs = ["HTML", "CSS", "JS", "Python"]
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.