Back

Activity 4.3 Arrays: Traversal & push()

divider

Introduction

Activity 4.3

Arrays: Traversal & push()

Topics

  • Traversing arrays with while loops
  • The traversal pattern: i, array.length, and array[i]
  • Common mistakes when traversing arrays
  • Adding new items with push()

Traversing Arrays

An array is most useful when you can work with all of its values. To do that, we use a loop to visit each element one-by-one. This process is called traversal.

In this lesson, you will traverse arrays to print every element, and then build a simple console task app that can grow over time.

The Traversal Pattern with while

The index variable starts at 0 and increases by 1 each loop. The loop stops when i < array.length becomes false.

// The standard traversal pattern
let i = 0;
while (i < array.length) {
console.log(array[i]);
i++;
}

Components of the Traversal Pattern

// The standard traversal pattern
let i = 0;
while (i < array.length) {
console.log(array[i]);
i++;
}

1. (let i = 0) Start at the first index.

2. (i < array.length) Stop before going past the last element.

3. (array[i]) Access the current element.

4. (i++) Move to the next index.

Demo 1: Traverse Cities

console.log("--- Demo 1: Traverse Cities ---");
let cities = ["Cleveland", "Chicago", "New York", "Dallas", "Seattle"];
let i = 0;
while (i < cities.length) {
console.log(i + ": " + cities[i]);
i++;
}
prompt("Press enter to continue...");

New Tool: push()

The push() function adds a new item to the end of an array. This is useful when your program needs a list that can grow over time.

// New Tool: push()
// push(value) adds a value to the END of an array.
let tasks = [];
tasks.push("Practice arrays");
tasks.push("Finish homework");
console.log(tasks); // ["Practice arrays", "Finish homework"]
console.log("Length:", tasks.length); // 2

Common Mistakes

1. Off-by-one condition: Using i <= array.length goes one past the end and can print undefined.

2. Forgetting i++: The loop never ends.

3. Starting at the wrong index: If you start at 1, you skip the first element.

Key Terms

Traversal
Visiting each element of an array one-by-one, usually from index 0 to index length-1.
array.length
The number of elements in an array. Used to stop a traversal loop safely.

Key Terms

push()
Adds a new element to the end of an array and increases its length by 1.
Off-by-one Error
A common mistake where a loop runs one extra time (or one too few times), often due to an incorrect loop condition.

'F' → Fullscreen

Objectives

  • icon Use a while loop to traverse an array.
  • icon Access elements using array[i].
  • icon Add new items using push().
  • icon Build a simple console app that displays a growing list.
divider

Activity Tasks

  • icon Create a new project named arrays-traversal.
  • icon Complete each task individually.

Task 1: Traverse Cities

  • icon Use the traversal pattern to print every city with its index.
  • icon Answer the quick check question as a code comment.
Task 1
console.log("--- Demo 1: Traverse Cities ---");
let cities = ["Cleveland", "Chicago", "New York", "Dallas", "Seattle"];
// Use a while loop to print every city in this format:
// 0: Cleveland
// 1: Chicago
// ...
let i = 0;
while (i < cities.length) {
console.log(i + ": " + cities[i]);
i++;
}
// (Quick Check): What would happen if you changed the loop condition to:
// while (i <= cities.length) ?
// Answer as a comment below.
prompt("Press enter to continue...");
// -----------------------------------------------------------------------------

Task 2: Simple Task App

  • icon Use prompt() to choose menu options.
  • icon Add tasks using tasks.push(newTask).
  • icon List tasks using a traversal while loop.
Task 2
22 collapsed lines
console.log("--- Demo 1: Traverse Cities ---");
let cities = ["Cleveland", "Chicago", "New York", "Dallas", "Seattle"];
// Use a while loop to print every city in this format:
// 0: Cleveland
// 1: Chicago
// ...
let i = 0;
while (i < cities.length) {
console.log(i + ": " + cities[i]);
i++;
}
// (Quick Check): What would happen if you changed the loop condition to:
// while (i <= cities.length) ?
// Answer as a comment below.
prompt("Press enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 2: Simple Task App ---");
let tasks = [];
let choice = "";
while (choice != "3") {
console.log("- Main Menu -");
console.log("1) Add task");
console.log("2) List tasks");
console.log("3) Exit");
choice = prompt("->");
if (choice == "1") {
let newTask = prompt("Enter task:");
tasks.push(newTask);
console.log(newTask + " added to tasks.\n");
}
else if (choice == "2") {
console.log("--Tasks--");
if (tasks.length == 0) {
console.log("No tasks to complete.");
}
let i = 0;
while (i < tasks.length) {
console.log("* " + tasks[i]);
i++;
}
console.log(); // Add spacing after list
}
else if (choice == "3") {
console.log("Exiting app.\n")
}
else {
console.log("Invalid option - Please try again.\n");
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1: Traverse Cities ---
0: Cleveland
1: Chicago
2: New York
3: Dallas
4: Seattle
Press enter to continue... [Enter]
--- Demo 2: Simple Task App ---
- Main Menu -
1) Add task
2) List tasks
3) Exit
-> 1
Enter task: Practice arrays
Practice arrays added to tasks.
- Main Menu -
1) Add task
2) List tasks
3) Exit
-> 1
Enter task: Pack gym clothes
Pack gym clothes added to tasks.
- Main Menu -
1) Add task
2) List tasks
3) Exit
-> 2
--Tasks--
* Practice arrays
* Pack gym clothes
- Main Menu -
1) Add task
2) List tasks
3) Exit
-> 3
Exiting app.
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Why must the traversal condition be i < array.length?
  2. What does push() do to an array?
  3. In the task app, why do we check tasks.length == 0 before printing tasks?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete