Uncaught TypeError: undefined is not a function

Hi everyone I’m currently a student working on a project out of my book, here is the code I am having the issue with.

for (var i = 0; i < numAsteroids; i++) {
    var radius = 5+(Math.random()*10);
    var x = canvasWidth+radius+Math.floor(Math.random()*canvasWidth);
    var y = Math.floor(Math.random()*canvasHeight);
    var vX = -5-(Math.random()*5);
    
    asteroids.push(new Asteroid(x, y, radius, vX));***<---line 21***
};

Now when I run this is keeps telling me I have an:

Uncaught TypeError: undefined is not a function line 21.

But I have the code exactly how it is in my book that’s what I don’t understand. If anyone could help me with this problem it would be great!

Answer

If the error is coming from this line because of the .push() method:

asteroids.push(new Asteroid(x, y, radius, vX));

Then, the issue is that asteroids has not been initialized as an array so thus it doesn’t have a method .push().

You can initialize it like this:

var asteroids = [];
for (var i = 0; i < numAsteroids; i++) {
    var radius = 5+(Math.random()*10);
    var x = canvasWidth+radius+Math.floor(Math.random()*canvasWidth);
    var y = Math.floor(Math.random()*canvasHeight);
    var vX = -5-(Math.random()*5);

    asteroids.push(new Asteroid(x, y, radius, vX));
}

It might also be possible to get this type of error if the Asteroid constructor function is not defined.

Leave a Reply

Your email address will not be published. Required fields are marked *