Skip to the content

Recursion with arrays

JavaScript · Unit 11: Recursion

An array can be split in two: the first item and the rest. You already know how, from the last unit: const [first, ...rest] = arr.

The rest is a shorter array, and that's exactly what recursion needs: a smaller problem.

const grades = [8, 6, 10];
const [first, ...rest] = grades;
console.log(first);
console.log(rest);

Prints

8
[ 6, 10 ]

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    The array has a single item. What does it print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Fill in addAll so it prints 13.

  4. 4. Find the bug

    This program should multiply all the numbers and print 24 (2 × 3 × 4). Which line has the error?

  5. 5. Find the case that fails

    maxOf(arr) should return the biggest number in the array, or null if it's empty. Which call breaks it?

  6. 6. Predict the output

    This function counts how many numbers there are, however deep they are. What does it print?

  7. 7. Complete the code

    Fill in flatten so it prints [ 1, 2, 3 ].

  8. 8. Put the lines in order

    Put maxAll in order. It finds the biggest number, even if it's inside other arrays.

  9. 9. Multiple choice

    What does all do?

  10. 10. Predict the output

    This time the first item goes at the end. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →