JAVASCRIPT / CHAPTER 04
Arrays and the first item
BeginnerKeep an ordered collection, read positions, and append an item.
By the end of this chapter
- Create an array literal
- Read and update a zero-based position
- Distinguish an array length from its last index
The idea
An array holds an ordered collection inside square brackets. Commas separate its items. For const tasks = ["read", "code"], tasks[0] is "read" and tasks[1] is "code". An array with two items has length 2 but last index 1. An empty array has length 0 and no first item.
Assignment to a position changes that item: tasks[0] = "review" replaces the first value. tasks.push("test") appends at the end and increases the length. const prevents assigning a different array to tasks; it does not make the array contents immutable. Say whether your operation is allowed to change its input before using a mutating method.
Start by tracing one array change at a time. Later, a loop will visit its items and a function will accept an array as an argument. The collection and copying chapters build on this picture; you do not need callbacks or nested copying to use your first array.
const tasks = ["read", "code"];
tasks[0] = "review";
tasks.push("test");
console.log(tasks[0]);
console.log(tasks.length);
console.log(tasks[tasks.length - 1]);review 3 test
Replacing an existing item leaves the length unchanged. Appending adds a third item at index 2.
Try it yourself
Make an array of two labels, replace the second label, append a third, and print the first and last values.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING