Recursion with arrays
JavaScript · Unit 11: Recursion
- Full plan
- JavaScript
- 10 exercises
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. Predict the output
The array has a single item. What does it print?
2. Predict the output
What does this code print?
3. Complete the code
Fill in
addAllso it prints 13.4. Find the bug
This program should multiply all the numbers and print 24 (2 × 3 × 4). Which line has the error?
5. Find the case that fails
maxOf(arr)should return the biggest number in the array, ornullif it's empty. Which call breaks it?6. Predict the output
This function counts how many numbers there are, however deep they are. What does it print?
7. Complete the code
Fill in
flattenso it prints[ 1, 2, 3 ].8. Put the lines in order
Put
maxAllin order. It finds the biggest number, even if it's inside other arrays.9. Multiple choice
What does
alldo?10. Predict the output
This time the first item goes at the end. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.