JavaScript and TypeScript course Β· Module 5: Advanced JavaScript

Basic Array Methods

6 min read Β·
In this lesson4

A raptor herd never stands still: in the morning a new animal joins the enclosure, in the evening another one goes to the vet, and someone else has to move to the front of the feeding line. Rebuilding the array from scratch after every change would be tiring, and it is easy to lose a dinosaur along the way. JavaScript offers a range of built-in methods that let you add, remove, and modify array elements. In the context of Jurassic Park, we need them to manage lists of dinosaurs, their status, and their location.

Array-Mutating Methods

The first group of methods changes the array in place. Every piece of code that uses the same array will see the effect.

push() - Adding to the End

The push() method adds one or more elements to the end of an array and returns the new array length:

const pack = ["Blue", "Charlie"];
console.log(pack.length); // 2

pack.push("Delta");
console.log(pack); // ["Blue", "Charlie", "Delta"]

// Adding multiple elements at once
pack.push("Echo", "Fox");
console.log(pack); // ["Blue", "Charlie", "Delta", "Echo", "Fox"]

The herd grew even though we declared it with const - a constant guards the assignment, not the contents of the array. Remember, too, that push() returns a number, not an array, so don't treat its result as a new herd.

pop() - Removing from the End

The pop() method works the other way round: it removes the last element from an array and returns it, so you know right away who left the herd:

const pack = ["Blue", "Charlie", "Delta", "Echo"];
const removed = pack.pop();

console.log(removed); // "Echo"
console.log(pack);    // ["Blue", "Charlie", "Delta"]

Echo disappears from the array but lands in the removed variable, so the entry can go straight to the vet. On an empty array pop() does not throw an error - it simply returns undefined.

unshift() - Adding to the Beginning

The unshift() method adds elements to the beginning of an array, shifting all existing elements one position further:

const pack = ["Charlie", "Delta"];
pack.unshift("Blue");

console.log(pack); // ["Blue", "Charlie", "Delta"]

Blue now has index 0, and Charlie moves to 1. Just like push(), unshift() returns the new length of the array.

shift() - Removing from the Beginning

The shift() method removes the first element from an array and returns it. It is the natural choice when you serve the feeding queue from the front:

const pack = ["Blue", "Charlie", "Delta"];
const first = pack.shift();

console.log(first); // "Blue"
console.log(pack);  // ["Charlie", "Delta"]

The names are easy to confuse, so remember the pair: shift() takes from the beginning, unshift() adds to the beginning. Both renumber all the remaining elements.

splice() - Versatile Modification

The splice() method can add, remove, or replace elements anywhere in the array. It modifies the original array. It takes a start index, the number of elements to remove and, optionally, new elements:

const dinosaurs = ["T-Rex", "Velociraptor", "Stegosaurus", "Triceratops"];

// Remove 1 element starting at index 1
dinosaurs.splice(1, 1);
console.log(dinosaurs); // ["T-Rex", "Stegosaurus", "Triceratops"]

// Insert an element at index 1 (without removing)
dinosaurs.splice(1, 0, "Brachiosaurus");
console.log(dinosaurs); // ["T-Rex", "Brachiosaurus", "Stegosaurus", "Triceratops"]

// Replace the element at index 2
dinosaurs.splice(2, 1, "Pteranodon");
console.log(dinosaurs); // ["T-Rex", "Brachiosaurus", "Pteranodon", "Triceratops"]

Every call returns an array of the removed elements - the first one would give back ["Velociraptor"]. The second shows that removing zero elements means a pure insertion, and the third combines a removal with an insertion, which is a replacement.

One Herd, Two Names

Before we move on to methods that don't mutate, meet a trap. Assigning an array to a new variable does not create a copy, just a second name for the same herd:

const pack = ["Blue", "Charlie"];
const nightShift = pack; // the same array, not a copy

nightShift.push("Delta");
console.log(pack);                // ["Blue", "Charlie", "Delta"]
console.log(nightShift === pack); // true

A change made through one name is visible under the other, because both variables hold a reference, a pointer to the same array in memory. This is the life cycle of data: the engine allocates memory when the array is created, your code uses it through references, and once the array is no longer reachable, the garbage collector frees it on its own. You will learn the details in the location about memory management.

Non-Mutating Methods

slice() - Copying a Portion of an Array

The slice() method returns a new array containing a portion of the original. It does not modify the original. The second argument is the index before which copying stops:

const allDinos = ["T-Rex", "Velociraptor", "Stegosaurus", "Triceratops", "Pteranodon"];

// slice(start, end) - from index start up to (but not including) end
const herbivores = allDinos.slice(2, 4);
console.log(herbivores); // ["Stegosaurus", "Triceratops"]
console.log(allDinos);   // Original unchanged!

// Copy the entire array
const copy = allDinos.slice();
console.log(copy); // ["T-Rex", "Velociraptor", "Stegosaurus", "Triceratops", "Pteranodon"]

The element at the end index is not included, which is why slice(2, 4) returns two dinosaurs. Calling it without arguments copies the whole array - the cure for the reference trap. The copy is shallow, though: the objects inside stay shared.

Key Difference: splice() vs slice()

Featuresplice()slice()
MutationYES - modifies the original arrayNO - returns a new array
Parameters(start, deleteCount, ...items)(start, end)
Use caseAdding/removing/replacing elementsExtracting a portion of an array

The names differ by one letter and the behavior by everything: splice() rearranges the herd, slice() takes a photo of part of it. When you don't need to change the original, I recommend slice() - code without unexpected mutations is easier to follow.

Method Chains: map, filter and forEach

Non-mutating methods have one more advantage: since they return a new array, you can call the next method on the result right away. That is how a chain is formed. Three methods show up in chains most often - map() transforms every element, filter() keeps only the matching ones, and forEach() performs an action for each:

const pack = ["Blue", "Charlie", "Delta", "Echo"];

const tags = pack.map(name => name.toUpperCase());
console.log(tags); // ["BLUE", "CHARLIE", "DELTA", "ECHO"]

const longNames = pack.filter(name => name.length > 4);
console.log(longNames); // ["Charlie", "Delta"]

// A chain: filter first, then transform
const alarms = pack.filter(name => name.length > 4).map(name => name + "!");
console.log(alarms); // ["Charlie!", "Delta!"]

pack.forEach(name => console.log("Present:", name)); // returns undefined
console.log(pack); // ["Blue", "Charlie", "Delta", "Echo"] - unchanged

map() always returns a new array of the same length, and filter() a shorter or equal one. forEach() returns only undefined, so the chain cannot continue after it. The last line confirms that the original herd was left untouched. A fourth method, reduce(), folds an array into a single value - we will deal with it in the next lesson.

In the lab below you will practice adding and removing raptors, and then splice() and slice().

Remember: mutating methods rearrange the herd in the enclosure, while non-mutating ones take its photo without moving a single raptor.

Code for this lesson: index.js
// Basic array methods - Managing a raptor pack

const pack = ["Blue", "Charlie"];
console.log("Starting pack:", pack);

// push() - add to the end
pack.push("Delta");
console.log("After push('Delta'):", pack);

// pop() - remove from the end
const removed = pack.pop();
console.log("After pop():", pack, "| Removed:", removed);

// unshift() - add to the beginning
pack.unshift("Alpha");
console.log("After unshift('Alpha'):", pack);

// shift() - remove from the beginning
const first = pack.shift();
console.log("After shift():", pack, "| Removed:", first);

// === EXERCISE ===
// TODO: Create an array dinosaurs with 5 dinosaurs
const dinosaurs = ["T-Rex", "Velociraptor", "Stegosaurus", "Triceratops", "Pteranodon"];

// TODO: Use splice() to remove 1 element starting at index 2
// TODO: Use splice() to insert "Brachiosaurus" at index 1

console.log("\n=== splice() ===");
console.log("After the splice operations:", dinosaurs);

// TODO: Use slice() to cut out the elements from index 1 to 3
// Remember: slice() does NOT modify the original array!
const fragment = dinosaurs.slice(1, 3);
console.log("\n=== slice() ===");
console.log("Fragment:", fragment);
console.log("Original unchanged:", dinosaurs);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the push() method do in a JavaScript array?

  2. 2. What is the difference between shift() and unshift() in arrays?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a pack array and add/remove Velociraptors using push, pop, shift, unshift.

  • Vertical ordering

    Arrange the syntax for creating an object with a nested array:

  1. QuestionArray Methods in Practice - push and pop
  2. QuestionArray Methods in Practice - shift and unshift
  3. Coding taskManaging the Pack Array
  4. QuestionArray Methods in Practice - slice and splice
  5. Put in orderObject Creation Syntax with Array
  6. QuestionArray Transformation with map()

Useful articles