LESSON 17 · BEGINNER4 min read

Arrays & Indexing

Store ordered lists, read and change items by position, and avoid common off-by-one errors.

ES2024 / Node.js 20+Free to readModule 4 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Create arrays and read items with zero-based indexes.
  • Choose between mutating methods and copying methods such as slice.
  • Iterate over arrays and access values inside nested arrays.

01Ordered values and zero-based positions

An array is an ordered list of values. Write items inside square brackets and separate them with commas. The first item sits at index 0, so the last item in an array of length 3 is at index 2. Access an item with brackets, such as tasks[0]. Reading beyond the end returns undefined rather than throwing, which is why checking length matters.

The length property is one more than the highest index in a normal array. Use tasks[tasks.length - 1] or the newer tasks.at(-1) to read the last item safely. at accepts negative indexes, while brackets do not. Empty arrays have length 0, and the valid index range is 0 through length - 1. A sparse or unusual array can break the length shortcut, but ordinary lists behave predictably.

indexing.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Grow and shrink at both ends

push adds to the end and returns the new length. pop removes and returns the last item. unshift adds to the front and returns the new length; shift removes and returns the first item. All four mutate the array in place. Choose them when the array is a stack or queue and mutation is intended. The name pop suggests taking something off a stack, while shift suggests serving the front of a queue.

shift and unshift move every remaining item, so they become expensive on very large arrays. For a long queue, consider an index or a different structure later. For beginner work, prefer the method whose name describes the operation, and log the returned value so you know whether it is the item or the length.

queue.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03slice copies; splice edits

slice(start, end) returns a new array containing items from start up to but not including end. End is optional. Negative indexes count from the end. slice does not change the original, which makes it the safe choice for a shallow copy: const copy = items.slice(). The spread syntax [...items] does the same job.

splice(start, deleteCount, ...items) changes the original array. It removes deleteCount items and optionally inserts replacements, then returns an array of the removed items. It is powerful and easy to misuse. If callers still need the original data, copy first or use the non-mutating toSpliced method.

slice-vs-splice.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Iterate and look inside nested arrays

for...of visits values, while entries() gives [index, value] pairs when the position matters. Avoid writing a loop that runs while index <= array.length; that reads one step past the end. The condition should be index < length. This off-by-one error is one of the most common array bugs.

An array can contain other arrays. Access a nested value with two indexes: grid[row][column]. Naming the outer and inner positions makes the code readable. If you only need a flat list, flat() removes one level of nesting; flatMap() combines a map and a flatten step. Do not guess coordinates; print the nested structure when a value comes back undefined.

matrix.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Array indexes start at 0, and the last valid index is length - 1.
  • push and pop work at the end; shift and unshift work at the start, and all four mutate.
  • slice copies a range, while splice edits in place and returns what it removed.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Move the first item to the end

Start with const steps = ['wash', 'dry', 'fold']. Remove the first item with shift, store it, add it to the end with push, and print the removed item and the final array.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const steps = ['wash', 'dry', 'fold'];const first = steps.shift();steps.push(first);console.log(first);console.log(steps);

shift removes wash and returns it. push then places that same string at the end, producing [ 'dry', 'fold', 'wash' ]. Both methods mutate steps, so no assignment back to steps is needed.

02

Exercise 2: Remove an item without mutating

Write removeAt(items, index) that returns a new array without the item at index. Return a copy unchanged when index is not a valid integer position. Print the result and the original array for ['a', 'b', 'c'] with index 1.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function removeAt(items, index) {  if (!Number.isInteger(index) || index < 0 || index >= items.length) {    return items.slice();  }  return [...items.slice(0, index), ...items.slice(index + 1)];}const original = ['a', 'b', 'c'];console.log(removeAt(original, 1));console.log(original);

The two slices take everything before and after the removed position, and spread joins them into a new array. The original is never changed. The output is [ 'a', 'c' ] followed by [ 'a', 'b', 'c' ].

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01In an array of length 4, what is the index of the last item?
02Which method changes the original array by removing or inserting items?
03What does ['a', 'b', 'c', 'd'].slice(1, 3) return?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Move the first item to the end

Start with const steps = ['wash', 'dry', 'fold']. Remove the first item with shift, store it, add it to the end with push, and print the removed item and the final array.

EXPECTED OUTPUT
wash
["dry","fold","wash"]
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.