# In the Mail Explainer

The aim of this puzzle: Complete the recursive `sendPostcards` function.

Walkthrough of the solution: In this puzzle, you’ll use a recursive function.

A recursive function is a function that calls itself, making the function run again. This makes the function work kind of like a loop, as it tells the computer to run the same block of code over and over. The function will keep calling itself until an end condition is met. Without this end condition, the function will not stop running

The `sendPostcards` function definition isn’t correct. It only sends 1 postcard. We need to make the function send all the postcards using recursion.

Inside the function, an if statement checks if `amount` is `1`. This is the same as asking if only 1 postcard needs to be sent. If only 1 postcard needs to be sent, then we should just print `'All postcards sent'` and return `amount`.

If `amount` isn’t `1`, more than 1 postcard needs to be sent and the `else` block will run. It will create a new variable called `amountRemaining`, which is just 1 less than `amount`. But how do we send `amountRemaining` postcards? Well, we could just call the `sendPostcards` function again, but this time with `amountRemaining`!

The important part is that each time the `sendPostcards` function is called, there is a check right away to see if only 1 postcard needs to be sent. Sending 1 postcard is the end condition that prevents the function from running forever.

Sample code solution:

(Tap below to reveal)

``````function sendPostcards(amount) {
console.log('Postcard ' + amount + ' sent!');
if (amount === 1) {
console.log('All postcards sent.');
return amount;
} else {
let amountRemaining = amount - 1;
console.log('Calling function again.');
return sendPostcards(amountRemaining);
}
}

sendPostcards(3);
``````

JavaScript Concepts: Code Block (function, if statement), `console.log()` , Recursion, `return`, Variables

Hi! Can I ask why within the if code block we have “return amount” called. What is the point of this? Thanks!

4 Likes

I have exactly the same question. I deleted the “return amount” and got the same result, only that grasshopper told me it was a mistake.

1 Like

I don’t understand the “- 1” in the let variable of the if else statement:

if (amount === 1) {
console.log(‘All postcards sent.’);
return amount;
} else {
let amountRemaining = amount - 1;
console.log(‘Calling function again.’);
return sendPostcards(amountRemaining

What does the “- 1” do?

In this case the amount is 3 and the -1 wil make amount 2 and the second time it wil make the amount 1.

Whiteout the return function JavaScript wil calculator but won’t return the answer.

/https://Error ???.hacked.profile/all/grasshopper/???/?

ERROR OF DATA_???

%%%%%55555555%5555%%55%

1;v ]

@grasshopperexplainer