Module 21: Arrays and Objects

Lesson 2 of 5 · 15–25 minutes

Array operations

🏠The everyday picture

A queue at a ticket counter: people join at the back, leave from the front, someone checks if a friend is in the queue, someone counts heads. Arrays have a built-in tool for each of these.

📘What it really is

Adding and removing:

Finding:

Copying and joining:

Changing in place (careful):

Some methods change the array; others return a new one and leave the original alone. Mixing them up is a classic source of bugs. Prefer the ones that return something new.

🖱️Try it

In catalogue.js:

const cart = ["Pen", "Notebook"];
cart.push("Bag");
console.log(cart.includes("Pen"));
console.log(cart.indexOf("Bag"));
const firstTwo = cart.slice(0, 2);
console.log(firstTwo, cart);
console.log(cart.join(", "));

Predict each output before you run it.

✅Quick check

indexOf returns -1. What does that mean?

Show the answer

The item isn't in the array.

Which changes the original array: slice or splice?

Show the answer

splice. slice returns a copy and leaves the original alone.

← PreviousRunning JavaScript with Node.js, and arrays
ProLearners Assist