Solution for Use a For loop instead of Recursion to Create a Range of NumbersChanging

Hi everyone,

is it possible to modify the function in order to use also a for-loop?

Can s.o. help me please?

Tell us what’s happening:

Your code so far


function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum){
  return [endNum];
}else {
  var number = rangeOfNumbers(startNum + 1, endNum);
  number.unshift(startNum);
  return number;
}
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

why don’t you try yourself first?

That’s what I did, but it does not work :frowning:

var arr = [ ];
function rangeOfNumbers(startNum, endNum) {
  if (startNum === endNum){
    return [endNum];
  }else {
    for (var i = startNum; i < endNum; i++){
      arr.push(i);
      return i;
    }
  }
}

Unfortunately, I am not sure what my mistake is.

What is the purpose of this line? You are returning after the first iteration of the for loop.

Also, if you want to include endNum in the array, you will need to modify your for loop condition.

Hi Randell,

thx for your help. The code below makes more sense and would be basically the same as the first one, or?

var arr = [];
function rangeOfNumbers(startNum, endNum) {
    for (var i = startNum; i <= endNum; i++){
      arr.push(i);
    }return arr;
}

Yes, but I would definitely not use arr as a global variable. I would make it local to the function.

Perfect, thanks a lot for ur help.