Gabuza
August 11, 2021, 9:10am
#1
Why I 'm I getting an error while trying to run the code? “arr.push is not a function”
**Your code so far**
function range(startNum, endNum) {
if(endNum === startNum) {
return startNum;
}
else if (startNum > endNum) {
return startNum + " is greater than " + endNum + " .Please enter a number smaller than or equal to " + endNum;
}
else {
var arr= range(startNum, endNum - 1);
arr.push(endNum);
return arr;
}
};
console.log(range(9,15));
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36
Challenge: Use Recursion to Create a Range of Numbers
Link to the challenge:
Gabuza:
function range(startNum, endNum) {
if(endNum === startNum) {
return startNum;
}
else if (startNum > endNum) {
return startNum + " is greater than " + endNum + " .Please enter a number smaller than or equal to " + endNum;
}
else {
var arr= range(startNum, endNum - 1);
arr.push(endNum);
return arr;
}
};
console.log(range(9,15));
Hi, this lesson is for recursion meaning that you should call the actual function ( it recursively should call itself).
arr.push(endNum);
is not the way you should call the actual function.
Gabuza
August 11, 2021, 9:19am
#3
How should I call it then?
Gabuza:
function range(startNum, endNum) {
if(endNum === startNum) {
return startNum;
}
else if (startNum > endNum) {
return startNum + " is greater than " + endNum + " .Please enter a number smaller than or equal to " + endNum;
}
else {
var arr= range(startNum, endNum - 1);
arr.push(endNum);
return arr;
}
};
console.log(range(9,15));
The issue was here :
Gabuza:
return startNum;
instead use : return [startNum];
I found it from here:
javascript, jquery, json
ilenia
August 11, 2021, 9:56am
#5
when you do this, you are getting the value returned from range
and putting it in a variable named arr
, later you use push
on that variable - remember that push
can work only on arrays, so you have to make sure that the value returned from range
is an array.
Let’s look at your return statements
this returns a number, not an array, so it causes errors in the recursion
this returns a string
1 Like
system
closed
February 9, 2022, 9:56pm
#6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.