Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:
can we make a solution using push?

  **Your code so far**
function countdown(n) {

if (n === 1) return [1];

const output = [n]; // [2]
return output.concat(countdown(n - 1)); // [2, 1]
}
function countdown(n) {
if (n === 1) return [1];

const output = [n]; // [2]
return output.push(countdown(n - 1)); // [2, 1]
}

why doesnt the second part work and what to do if we want to use .push

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

Read the documentation on the push method, particularly what it returns.

MDN: Array.prototype.push()

Also, your base case is not quite right.

function countdown(n) {
if (n<1){
  return[]
}else{
  const output = [n]; // [2]
  return output.concat(countdown(n - 1)); 
}}

my question is push adds one or more elements to the end of an array
so why cant we use use push to add the string(concating)

Did you follow that link and look at the return value of the push() method?

Return value:
The new length property of the object upon which the method was called.

myArray.push(newElement) evaluates to a number and then you are returning that number.

you can, but you can’t use the exact code you posted

then how can i do it with push to make a solution for https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

look at Jeremy posts, he is talking about that

Well, try not putting the call to push on the same line as your return. How can you make that work?

so uh what about this

function countdown(n) {
if (n<1){
  return[]
}else{
  const output = [n]; // [2]
  let x = output.push(countdown(n - 1)); 
  return x
}}

Why are you returning x. You just very elaborately recreated the exact same issue.

const myArray = [1, 2, 42, 13];
let pushReturn = myArray.push(1000);
console.log("return value:", pushReturn);
console.log("myArray:", myArray);

When you call a function, that function call returns some sort of value. In this case, calling push() returns an NUMBER, not an ARRAY. Your function countdown() must return an ARRAY, so you cannot return the return value of the call to push().

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.