Data Structures
Array
Read by index: O(1), instant · Add or remove at the end: O(1) · Search for a value: O(n)
The idea, in plain English
An array is like an egg carton. It has a row of numbered slots, and each slot holds one thing. The slots stay in order. Each slot has a number, called its index. The first index is 0.
How it works
- 1Put items in a row of slots, in order.
- 2Reach any item right away by its slot number. This number is called the index, and it starts at 0.
- 3Add an item to the end, remove one from the end, or loop through every slot.
When you'd use it
You'll use arrays almost everywhere. Use one whenever you have a list of things in a specific order, like a to-do list, search results, or the players in a game.
Common beginner mistakes
- You may forget indexes start at 0. So the first item is arr[0], not arr[1].
- Don't go past the end of the array, like arr[arr.length]. There's nothing there.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Items: apple, banana, cherry, date
Count: 4
First: apple
Removed: dateSee it in motion
Ready. Press play — read by index is instant, but inserting or deleting shifts the rest.
Not sure this is the right topic? See the learning paths → or where this leads →