A Recursive Roll explainer

Aim of this puzzle:
This puzzle introduces the concept of recursion. You’ll update a function and its array of possible inputs to include an input that makes the function run again.

Walk through of the solution:
Recursion is when a function repeatedly calls itself from inside its own code block until an end condition is met (known as the base case).

In the code that you start off with, a value, roll, is picked at random from the rolls array and used as an argument to the withRecursion and noRecursion functions. The noRecursion function takes roll and simply returns it. The withRecursion function takes roll and compares it to the value 7. If roll is 7, 'You rolled a 7. Rolling again…' is output, a nextRoll is selected, and noRecursion is called using nextRoll as an argument. If roll isn’t 7, then roll is returned. As it is, the withRecursion function is incorrect and the rolls array doesn’t have a 7. In this puzzle, you’ll add 7 to the rolls array and update the return statement inside withRecursion to make it recursive.

To complete the puzzle, add 7 two times to the rolls array and change the return statement inside withRecursion from noRecursion(nextRoll) to withRecursion(nextRoll).

Tap the play button on the Example Solution a few times.You can see the difference between a roll that lands on 7 using noRecursion and withRecursion. The noRecursion function simply returns 7, whereas withRecursion re-runs each time it lands on 7 and keeps running until roll isn’t 7.

Sample code solution:
(Tap below to reveal)

let rolls = [1, 2, 3, 4, 7, 7]
let roll = pickRandom(rolls)

function withRecursion (roll) {
    if (roll === 7 ){
        console.log('You landed on 7. Rolling again...')
        let nextRoll = pickRandom(rolls)
        return withRecursion(nextRoll)
    } else {
        return roll

function noRecursion (roll){
    return roll

console.log('You rolled a: ' + withRecursion(roll))
console.log('You rolled a: ' + noRecursion(roll))

JavaScript Concepts: Variable, Function, Recursion
Grasshopper Concepts: pickRandom()


if i’m not mistaken, it’s same with while, isn’t it ?

1 Like