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.
ilenia
August 3, 2022, 7:08pm
5
you can, but you can’t use the exact code you posted
ilenia
August 3, 2022, 7:10pm
7
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()
.
system
Closed
February 2, 2023, 7:20am
11
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.