Abhishek Singh
Abhishek Singh

Reputation: 63

why does this function not work? I want it to count backwards from 10 to 1

I want it to count backwards from 10 to 1.

function countdown(n) {
  if (n < 1) {
    return []
  } else {
    return countdown(n - 1).unshift(n);
  }
}

Upvotes: 1

Views: 99

Answers (2)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

The value returned by the function isn't an array. unshift has to be used only on array objects. There's many much simpler way to achieve what you are trying to do here.

I have mentioned a simple recursive function which achieves the same -

function countdown(n) {
  console.log(n)
  // recursive till n becomes zero. When n === 0, just return 0
  return n ? countdown(n - 1) : 0;
}

countdown(10)


NOTE : The method you are using - unshift() returns new length property of the object upon which the method was called. So, if you want to have a countback array to be returned from the function, you could choose to use the following approach which uses recursion and unshift(), just as in your code with slight changes in code -

function countdown(n) {
  if (n < 1) {
    return []
  } else {
    let z = countdown(n - 1);
    z.unshift(n);
    // return the array itslef so unshift() would work. Directly returning z.unshift would result in returning a number and not an array.
    return z;
  }
}
// will return countdown array
console.log(countdown(10))

There will probably be a better way to do this without using unshift() or recursion...but I have just shown an approach which can be used to achieve the desired result.

Upvotes: 1

DCR
DCR

Reputation: 15685

unshift works on arrays. n is a number.

function countdown(n){
  if (n < 1) {
    console.log(n)
    return n
  } else {
    console.log(n)
    return countdown(n-1);
  }
}

countdown(10)

Upvotes: 1

Related Questions