Function that counts down a number in an array

Hi everyone,

I’ve been working on this code and been having some trouble with it. I think it has something to do with the for loop.
This function should take a number, and create an array of numbers counting down from this number to 0.

function countdown(start) {
	for (let i = 0; i <= start; i++) {
		start.push[i];
		}
	return start.reverse();
}

I keep getting this error…

TypeError: Cannot read property '0' of undefined
    at countdown

I cannot seem to find out what the problem is… Is there anyone that can possibly help me with this?

Thanks,
Peter

Hello there,

push is an array method. This means is it called like a function: myArray.push()

The current code is trying to index into it .push[0] which cannot happen, unless you have defined start like this:

const start = { push: [1, 2, 3, 4] }; // Just an example

Hope this clarifies

2 Likes

Got it!

function countdown(start) {
	var myArray = [];
	for (let i = 0; i <= start; i++) {
		myArray.push(i);
		}
	return myArray.reverse();
}

This seemed to solve it. Thanks alot!

-Peter