cikatomo
cikatomo

Reputation: 1632

What is multiply in recursion?

I am learning recursion and found code similar to this:

function repeat(operation, num) {

    if (num < 1) return console.log('eee')
    console.log(num)
    return operation() * repeat(operation, num - 1)
}

function operation(){
    console.log('lll')
}

repeat(operation, 5)

If I run I get this:

5
lll
4
lll
3
lll
2
lll
1
lll
eee

If I switch the last line like this:

return repeat(operation, num - 1) * operation()

I get this:

5
4
3
2
1
eee
lll
lll
lll
lll
lll

Why is that? What is multiply doing exactly there?

Upvotes: 1

Views: 60

Answers (1)

Eriks Klotins
Eriks Klotins

Reputation: 4180

In your example, multiply is not used to multiply. It is used as a trick to change the order of function calls. Try replacing * with + and you will get the same result.

To demonstrate the concept:

function one(x){ console.log('one')}
function two(x){ console.log('two')}

one() * two() 
// gives:
// one
// two

two() * one()
// gives:
// two
// one

the result of both expressions is NaN

UPDATE: The output represents the order of how functions are called. In the first case, repeat() gets called, calls operation() then repeat() again until num<1. This way you get alternating output. In the second case, you call repeat() until num<1 then step out from the recursion and call operation() a number of times.

Upvotes: 2

Related Questions