W
W
weredy2016-10-21 14:22:34
JavaScript
weredy, 2016-10-21 14:22:34

Is it correct to make loops recursive?

JS example:

function test(){
  rnd = Math.floor(Math.random() * 10);
  //console.log(rnd);
  if (rnd==6)
    return rnd;
  else
    return test();
}

console.log(test());

Is it allowed to do so? If not, I'd like to understand why.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2016-10-21
@riky

an example of heresy.
because all this is replaced by

function test(){
   return 6;
}

But in general, who forbids you, consider just an extra function call - an extra resource overhead.
but if you have only a few iterations there, then of course no one will notice it.

R
Rsa97, 2016-10-21
@Rsa97

In JS, this is incorrect, since trailing (tail) recursion is not supported.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question