Codiqo

Learn JavaScript · lesson 50 of 60 · about 8 minutes

Recursion on Arrays and Strings

Handle the first item, then let a recursive call handle the rest.

What you'll learn

  • Split an array into its first item and the rest
  • Recurse over a string
  • Stop at an empty array or string

What Sam is revising

Sam's flashcards cover different topics, and the page should say what Sam is revising the way a person would write it: Revising arrays and basics, or Revising arrays, basics and strings for three. That's recursion on an array: the first topic and a comma, then the rest of the list said the same way, until only two are left to join with and. The flashcards already worked out topics, sorted and without repeats.

First and the rest

An array is its first item plus the rest of the array. arr[0] is the first item and arr.slice(1) is everything after it.

So the total of an array is arr[0] plus the total of arr.slice(1). The base case is the empty array, whose total is 0.

Adding up an array

function total(arr) {
  if (arr.length === 0) return 0;
  return arr[0] + total(arr.slice(1));
}

console.log(total([4, 1, 5]));
console.log(total([]));

Output

10
0

Strings work the same way

s[0] is the first character and s.slice(1) the rest. To reverse a string, reverse the rest and put the first character on the end.

Reversing text

function reverse(s) {
  if (s === "") return "";
  return reverse(s.slice(1)) + s[0];
}

console.log(reverse("phoebe"));

Output

ebeohp

More than one base case

A list can stop at more than one size. Sam's joinAnd needs one for each shape it can't split any further: no words gives nothing, one word is just that word, and two words are joined with and. Only longer lists split into the first word and the rest.

Spacing out a title

function spaced(s) {
  if (s.length <= 1) return s;
  return s[0] + " " + spaced(s.slice(1));
}

document.querySelector("#title").textContent = spaced("SAM");
console.log(document.querySelector("#title").textContent);

Output

S A M

Tip

Loops and array methods are usually simpler for flat arrays. Recursion really shines on data inside data, which you'll meet in the project.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.