JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 6: Arrays and CollectionsLesson 26 of 150About 40 minutes

Lesson 26: Creating and accessing arrays

01Opening question

A playlist holds 300 songs. Would you create 300 variables, or is there a way to keep them all in one place and still reach any single song?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Square brackets create the array and square brackets read from it. The first position is 0.

const songs = ["Intro", "Sunrise", "Drive"];
console.log(songs[0]);
console.log(songs.length);
console.log(songs[songs.length - 1]);

03Objective and prerequisites

Learning objective: Create arrays with literals, read and change elements by index, use length and at(), and explain why arrays start at index 0.

You need: Lesson 16: For loops, Lesson 25: Combining functions into applications

Skills practised: Arrays, Working with collections.

04Explanation

An array is an ordered list of values written in square brackets: ["Tea", "Cake", "Juice"]. One variable holds the whole list.

Each value is an element and has a numbered position called an index. Indexes start at 0, so the first element is list[0] and the second is list[1].

list.length tells you how many elements there are. The last element is at list.length - 1, or you can write list.at(-1).

You can change an element by assigning to its index: list[1] = "Scone";. This works even when the array is declared with const, because the variable still points to the same array.

05Definitions

Array
An ordered list of values stored in one variable.
Element
One value stored in an array.
Index
The numbered position of an element, starting at 0.
length
The number of elements in an array.
at()
Reads an element by index; negative numbers count from the end.

Open the full glossary

06Visual learning object

Array indexing visualizer. Type an array and an index and see which cell is read, with positive and negative indexes.

Loading the interactive object…

Open the full Array indexing visualizer page with its guided experiment.

07Examples

ex-026-01Create and read an array Browser-executable JavaScript

Indexes start at 0; length counts the elements.

const menu = ["Tea", "Coffee", "Juice"];
console.log(menu);
console.log(menu[0], menu[2]);
console.log("Items:", menu.length);
Sample input
None
Expected output
["Tea", "Coffee", "Juice"] Tea Juice Items: 3
Common mistake
Expecting menu[1] to be the first item.
Try this
Print the second item.
Source
examples/ex-026-01-create-and-read.js

ex-026-02The last element Browser-executable JavaScript

length - 1 and at(-1) both reach the end.

const queue = ["Ada", "Grace", "Linus", "Margaret"];
console.log(queue[queue.length - 1]);
console.log(queue.at(-1));
console.log(queue.at(-2));
console.log(queue[queue.length]);
Sample input
None
Expected output
Margaret Margaret Linus undefined
Common mistake
Writing queue[queue.length], which is one past the end.
Try this
Print the first person with at().
Source
examples/ex-026-02-last-element.js

ex-026-03Changing an element Browser-executable JavaScript

Assigning to an index replaces that element, even in a const array.

const seats = ["free", "free", "free"];
seats[1] = "taken";
console.log(seats);
console.log(seats.length);
Sample input
None
Expected output
["free", "taken", "free"] 3
Common mistake
Thinking const stops the array from changing.
Try this
Mark the last seat taken using length.
Source
examples/ex-026-03-change-element.js

ex-026-04Calculating with elements Browser-executable JavaScript

Elements are ordinary values, so you can calculate with them.

const temps = [18, 22, 25];
const first = temps[0];
const last = temps[temps.length - 1];
console.log("Rise:", last - first);
console.log("Average of ends:", (first + last) / 2);
Sample input
None
Expected output
Rise: 7 Average of ends: 21.5
Common mistake
Forgetting parentheses around the sum before dividing.
Try this
Add a fourth temperature and check the code still works.
Source
examples/ex-026-04-numbers-array.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the last item

Read the last element correctly.

const tasks = ["Plan", "Build", "Test", "Ship"];
const lastTask = tasks[tasks.length];
console.log("Last task:", lastTask);

Update the scoreboard

Change elements by index.

const scores = [10, 14, 9];
// TODO: add 5 to the second score and set the last score to 12
console.log(scores);

Safe element lookup

Validate an index before reading.

const products = ["Lamp", "Rug", "Chair"];

09Prediction

Commit to an answer first, then run the real code to compare.

const a = [5, 10, 15];
a[0] = a[1] + a[2];
console.log(a[0], a.length, a.at(-1));

What is printed?

10Debugging investigation

The leaderboard shows second place as the winner

The scores are already sorted from highest to lowest, but the banner names the second-place player as the winner.

const players = ["Ada", "Grace", "Linus"];
const winner = players[1];
console.log(`Winner: ${winner}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Today's specials board

A café screen shows today's specials from an array. Staff add and change items, and the screen always shows the first special as the headline and the count underneath.

const specials = ["Soup", "Pie", "Salad"];
console.log(`Headline: ${specials[0]}`);
console.log(`${specials.length} specials today`);

12Knowledge check

1. What is printed?

const x = ["a", "b", "c"];
console.log(x[1]);
  • a
  • b
  • c
  • undefined

2. What is the index of the last element in an array of 8 items?

  • 8
  • 7
  • 0
  • -1

3. What is printed?

const x = [1, 2];
console.log(x[5]);
  • An error
  • undefined
  • null
  • 0

4. Why does this throw TypeError: Assignment to constant variable?

const list = [1, 2];
list = [3, 4];
  • Arrays cannot change
  • The whole variable is reassigned
  • Index 0 does not exist
  • const arrays are frozen

5. What is printed?

console.log(["a", "b", "c"].at(-2));
  • 3
  • c
  • b
  • undefined

6. Which reads the last element and keeps working when the list grows?

  • list[2]
  • list[list.length - 1]
  • list[list.length]
  • list[-1]

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the last item: Prints Ship; Not hard-coded
  • Update the scoreboard: Prints the updated array; scores is updated
  • Safe element lookup: Prints three results; Rejects 1.5; Reads index 0
  • ex-026-01: output matches the documented expected output
  • ex-026-02: output matches the documented expected output
  • ex-026-03: output matches the documented expected output
  • ex-026-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-06-arrays-and-collections/lesson-026-creating-and-accessing-arrays/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Arrays hold ordered values in square brackets.
  • Indexes start at 0; the last is length - 1 or at(-1).
  • Missing indexes give undefined.
  • const stops reassignment, not changes to elements.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation arrays
Context: I am learning arrays in JavaScript.
Task: Explain arrays, indexes and length with a playlist example and a drawing of the index positions.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction arrays drill
Context: I have practised arrays.
Task: Ask me eight questions about reading elements by index, including negative at() indexes.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging arrays bug
Context: My program prints undefined when I read the last element of my array.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation arrays practice
Context: I finished the arrays exercises.
Task: Create three exercises that read and change elements of shopping and score arrays.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review arrays review
Context: Here is my code that uses arrays.
Task: Review how I read and update elements and point out any off-by-one risks.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.