AI Hints
JavaScript · Lesson 43 of 138

Arrays

Lists of values.

⏱ 2 min read▶ Video at 52:09🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A shopping list, a playlist, the scores in a game. Programs are full of lists. In JavaScript, a list is called an array, and it keeps its values in order.

Arrays
From the video: Arrays
  • Shopping lists, playlists, scores
  • Programs are full of lists
  • Arrays

Making and reading arrays

Square brackets make an array, with values separated by commas. Each value has a position, called an index, starting at zero. So fruits at zero is the first fruit. Length tells you how many items there are, and length minus one is the last index. Run it.

app.jsjavascript
const fruits = ["apple", "banana", "cherry"];

console.log(fruits);
console.log(fruits[0]);
console.log(fruits.length);
console.log(fruits[fruits.length - 1]);
console.log(fruits.at(-1));
Output
[ 'apple', 'banana', 'cherry' ]
apple
3
cherry
cherry

Changing items

You can replace an item by assigning to its index, like fruits at one equals blueberry. That works even though fruits is a const, because const stops you replacing the whole array, not changing what's inside it. Arrays can hold any type, even a mix, but usually they hold one kind of thing.

keyvalue
[a, b, c]make an array
arr[0]first item
arr.lengthhow many
arr.at(-1)last item

Summary

Arrays hold values in order, starting at index zero. Length counts them, and at minus one gets the last. Next, adding and removing items.

Key takeaways
  • [ ] makes an array
  • Index from 0
  • length and at(-1)
Next up: Adding and Removing — push, pop, shift, unshift