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

Lesson 27: Adding and removing elements

01Opening question

When you add a product to a cart or remove one, the list changes size. Which tools change an array, and which ones leave it alone?

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

push and pop work at the end; unshift and shift work at the start.

const cart = ["Pen"];
cart.push("Notebook");
cart.unshift("Bag");
console.log(cart);
const removed = cart.pop();
console.log(removed, cart);

03Objective and prerequisites

Learning objective: Add and remove elements with push, pop, unshift, shift and splice, copy parts with slice and concat, and tell mutating methods from non-mutating ones.

You need: Lesson 26: Creating and accessing arrays

Skills practised: Arrays, Array methods.

04Explanation

push(x) adds to the end and pop() removes the last element and returns it. unshift(x) adds to the start and shift() removes the first element.

splice(start, deleteCount, ...items) removes or inserts elements anywhere: list.splice(1, 1) removes one element at index 1.

These five methods mutate (change) the original array. slice(start, end) and concat() do not: they return a new array and leave the original as it was.

Read a method's return value: push returns the new length, pop and shift return the removed element, splice returns an array of removed elements.

05Definitions

push / pop
Add to or remove from the end of an array.
unshift / shift
Add to or remove from the start of an array.
splice
Removes or inserts elements at any index, changing the array.
slice
Returns a copy of part of an array without changing it.
Mutation
Changing an existing value in place instead of creating a new one.

Open the full glossary

06Visual learning object

Array operation explorer. Apply push, pop, splice, slice and more to an array and compare the original afterwards with the value returned.

Loading the interactive object…

Open the full Array operation explorer page with its guided experiment.

07Examples

ex-027-01Working at the end Browser-executable JavaScript

push adds, pop removes and returns the removed element.

const stack = ["A", "B"];
const newLength = stack.push("C");
console.log(stack, newLength);
const top = stack.pop();
console.log(top, stack);
Sample input
None
Expected output
["A", "B", "C"] 3 C ["A", "B"]
Common mistake
Expecting push to return the array.
Try this
Push two items in one call: push("D", "E").
Source
examples/ex-027-01-end-operations.js (repository pending publication)

ex-027-02Working at the start Browser-executable JavaScript

unshift adds to the front; shift serves the front of a queue.

const queue = ["Ada", "Grace"];
queue.unshift("Linus");
console.log(queue);
const served = queue.shift();
console.log("Serving", served, "next:", queue[0]);
Sample input
None
Expected output
["Linus", "Ada", "Grace"] Serving Linus next: Ada
Common mistake
Mixing up shift (remove) and unshift (add).
Try this
Add a VIP to the front, then serve two people.
Source
examples/ex-027-02-start-operations.js (repository pending publication)

ex-027-03Removing from the middle Browser-executable JavaScript

splice changes the array and returns what it removed.

const items = ["Lamp", "Rug", "Chair", "Desk"];
const removed = items.splice(1, 2);
console.log(removed);
console.log(items);
items.splice(1, 0, "Plant");
console.log(items);
Sample input
None
Expected output
["Rug", "Chair"] ["Lamp", "Desk"] ["Lamp", "Plant", "Desk"]
Common mistake
Reading the second number as an end index; it is a count.
Try this
Replace Desk with Sofa using one splice call.
Source
examples/ex-027-03-splice-middle.js (repository pending publication)

ex-027-04slice and concat do not mutate Browser-executable JavaScript

The original stays the same; a new array is returned.

const week = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const midweek = week.slice(1, 4);
const all = week.concat(["Sat", "Sun"]);
console.log(midweek);
console.log(week.length, all.length);
Sample input
None
Expected output
["Tue", "Wed", "Thu"] 5 7
Common mistake
Expecting slice's end index to be included.
Try this
Use slice(-2) to get the last two days.
Source
examples/ex-027-04-slice-copies.js (repository pending publication)

08Guided exercises

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

Remove the right item

Use splice with an index and a count.

const playlist = ["Intro", "Sunrise", "Drive", "Outro"];
playlist.splice(2);
console.log(playlist);

Manage the queue

Combine push and shift.

const queue = ["T1", "T2"];
// TODO: T3 and T4 join the end; then serve (remove) the first two tickets
console.log("Served:", served.join(", "));
console.log("Waiting:", queue.join(", "));

One page of results

Use slice to read a page without changing the data.

const results = ["r1", "r2", "r3", "r4", "r5", "r6", "r7"];
const PAGE_SIZE = 3;

09Prediction

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

const a = [1, 2, 3];
const b = a.slice(1);
const c = a.splice(1, 1);
console.log(a, b, c);

What is printed?

10Debugging investigation

Showing a preview empties the cart

After the cart preview shows the first two items, the cart total only counts the last item.

const cart = ["Tea", "Mug", "Cake"];
const preview = cart.splice(0, 2);
console.log("Preview:", preview.join(", "));
console.log("Items in cart:", cart.length);

More cases in the Debugging Detective Laboratory

11Practical scenario

Shopping cart actions

A cart adds items with push, removes a chosen line with splice, and shows a preview of the first three items with slice so the cart itself never changes while it is displayed.

const cart = ["Tea", "Mug", "Cake", "Jam"];
cart.splice(1, 1);
console.log(cart.slice(0, 2));
console.log(cart.length);

12Knowledge check

1. What is printed?

const a = [1, 2];
console.log(a.push(3));
  • 3
  • [1, 2, 3]
  • undefined
  • 2

2. Which method does NOT change the original array?

  • push
  • splice
  • slice
  • shift

3. What is printed?

console.log(["a", "b", "c", "d"].slice(1, 3));
  • ["b", "c"]
  • ["a", "b"]
  • ["b"]
  • ["a"]

4. Why is the wrong item removed?

const i = list.indexOf("Rug");
list.splice(i);
  • splice needs a count
  • indexOf is used correctly but splice(i) removes to the end
  • pop should be used
  • Arrays cannot remove from the middle

5. What does shift return?

  • The new length
  • The removed first element
  • A new array
  • Nothing

6. A function receives a shared list and must add an item without affecting other code. Which is safer?

  • list.push(item); return list;
  • return [...list, item];
  • Both are the same
  • list.unshift(item)

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.

  • Remove the right item: Only Drive removed
  • Manage the queue: Prints both lines; Uses shift
  • One page of results: Prints three pages; Original unchanged; Page 4 is empty
  • ex-027-01: output matches the documented expected output
  • ex-027-02: output matches the documented expected output
  • ex-027-03: output matches the documented expected output
  • ex-027-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-027-adding-and-removing-elements/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • push/pop work at the end, unshift/shift at the start.
  • splice removes or inserts anywhere and mutates.
  • slice and concat return new arrays.
  • Check what each method returns.

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 array mutation methods
Context: I am learning array mutation methods in JavaScript.
Task: Explain push, pop, shift, unshift, splice and slice with a cart example, marking which ones change the array.
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 array mutation methods drill
Context: I have practised array mutation methods.
Task: Give me eight short programs using these methods and ask what each prints.
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 array mutation methods bug
Context: My splice call removes more items than I wanted.
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 array mutation methods practice
Context: I finished the array mutation methods exercises.
Task: Create three exercises using push, splice and slice with exact expected output.
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 array mutation methods review
Context: Here is my code that uses array mutation methods.
Task: Review where my code mutates shared arrays and suggest non-mutating alternatives.
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.