Recursive function JS

Asked

Viewed 149 times

0

I’m studying a little recursive function and I came across an exercise that’s taking my sleep, because it’s a basic exercise and I don’t understand the way out. Basically the book asks to create a function to test whether a number is PAR or not, returning a boleano value. But the function would have to meet the following requirements.

se o valor passado for 0 return true
se o valor passado for 1 return false
para qualquer outro valor faça n - 2 ate reduzi-lo a 0 ou 1.

my job was like this:

function epar(x){
    if(x==0){
        return true
    }
    else if(x==1){
        return false
    }
    else{
        epar(x-2)
    }
}
console.log(epar('parametro'))

What they don’t understand is that when I put some value other than 1 or 0, it returns a Undefined value. I did some tests for example printing the value passed each time I returned the function and actually the value decreases as I would like, but for some reason it tao ta returning neither true nor false.

  • you have to give return in that epar(x-2), otherwise the function returns nothing in this recursive cycle.

  • You need to return the value, within the else must be return epar(x-2). And since this function only works with numbers, it doesn’t make sense to call by passing a string, so it should be something like console.log(epar(5)) (step 5 or any other paragraph, as it makes no sense to pass the text 'parametro' if she only works with numbers)

  • I understand, thank you very much, this value ai ta a string so to illustrate that would be passing any parameter, I was passing numbers, I will test with the thank you Return

1 answer

1

You have to give return in that epar(x-2), otherwise the function returns nothing and this recursive cycle does not pass the result out.

function epar(x) {
  if (x == 0) {
    return true
  } else if (x == 1) {
    return false
  } else {
    return epar(x - 2)
  }
}
console.log(epar(24));
console.log(epar(23));

  • 1

    Thank you very much, I didn’t know that!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.