I was trying to use for loop for the countUp challenge but it wont work. why is that?

var myArray=[]
function countUp(n){
     for (i = 1; i<n ;i++){
          myArray.push(i)
     }
return myArray
}

What is the link for that challenge? What are you trying to do?

var myArray=
function countUp(n){
for (i = 1; i<n ;i++){   <------ look closer at this line
myArray.push(i)
}
return myArray
}

OK, so you’re trying to duplicate the example code? Of course the purpose of the example code was to demonstrate recursion and you’re trying to do it without recursion. But OK. I see a couple of things:

  1. You are using a global variable myArray. Global variables are usually a bad idea. Move that into the function.
  2. You never declare your variable i. That is always a bad practice. Most people would write: for (let i = 1; ...
  3. There is a slight problem with your logic. If you put a console.log(i) in your loop, you should be able to see the issue. I assume that this is what @nsgxyz was pointing out.

When I deal with each of those, it runs and does what the example code does. Take that information and see if you can get it to work. If you get stuck, check back and we’ll see about some better hints.

1 Like

" Your function must use recursion by calling itself and must not use loops of any kind."
This is part of the challenge description. You are not supposed to use loops and you must use recursion, the concept explained in the lesson. The example code only shows how the task would be done with a loop, its up to you, to transform it as recursive function. There is another big joker in the challenge description- “If the function is called with a number less than 1, the function should return an empty array”. It can help you a great deal if you set that condition in the start of your function.