Uncaught ReferenceError: Car is not defined

I am following along with the video titled " Self-Driving Car with JavaScript Course – Neural Networks and Machine Learning" and have the Live Code extension running on vscode while the files are stored in Windows Subsystem Linux 2. I am encountering an Uncaught Reference Error for the Car class on main.js:6:11. I’ve tried using console.log to pin point the problem, which seems to reside from the car class with no clear syntax error. I have also tried clearing the cache from Chrome where I’m viewing the code behavior. Here is the main.js code along with the index.html and car class files below.

<!DOCTYPE html>
<head>
    <title>Self-driving car - No Libraries</title>
</head>
<body>
    <canvas id="myCanvas"></canvas>
    <script src="main.js"></script>
    <script src="car.js"></script>
</body>
</html>

const canvas=document.getElementById("myCanvas");
canvas.height=window.innerHeight;
canvas.width=200;

const ctx = canvas.getContext("2d");
const car=new Car(100,100,30,50);

class Car{
    constructor(x,y,width,height){
        this.x=x;
        this.y=y;
        this.width=width;
        this.height=height;
    }

    draw(ctx){
        ctx.beginPath();
        ctx.rect(
            this.x-this.width/2,
            this.y-this.height/2,
            this.width,
            this.height
        );
        ctx.fill();
    }
}

I read recently that uploading the git repo is better, so here. Thank you in advance.

Hi @MathBevans !

Welcome to the forum!

I found the video you are working through.
I would personally use import/export statements but it looks like they are using an alternative route.

It looks like you are missing a few things in your code.

NO.1:
You need to link you stylesheet to the html document in order for your styles to show up

<head>
    <title>Self-driving car - No Libraries</title>
    <link rel="stylesheet" href="style.css">
</head>

No.2:
You need to load the car script before the main script.

<body>
    <canvas id="myCanvas"></canvas>
     <script src="car.js"></script>
    <script src="main.js"></script>
   
</body>

No.3:
In order for the car to show up, you need to add draw method to your main.js file

const ctx = canvas.getContext("2d");
const car = new Car(100, 100, 30, 50);
car.draw(ctx);

Then the error should go away and the black car should show up on the screen.

Thank you! Seems I forgot that functions need to be called. Why does the order of the scripts matter in the case of html, if you don’t mind me asking?

Since the main.js script relies on the code from car.js, you need to load the car.js script first.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.