DEV Community

Cover image for How to Debug JS Errors Using ChatGPT(Beginner's Guide)
Janani Jayakumar
Janani Jayakumar

Posted on

How to Debug JS Errors Using ChatGPT(Beginner's Guide)

Everyone makes mistakes while coding. The good news is that AI tools like ChatGPT can help you understand and fix JavaScript errors faster.
In this blog, you'll learn how to use ChatGPT to debug common Javascript errors with real examples.

Error1:

Reference Error

console.log(username);
Enter fullscreen mode Exit fullscreen mode

Output:

ReferenceError: username is not defined
Enter fullscreen mode Exit fullscreen mode

Prompt to ChatGPT:
Explain why I'm getting ReferenceError: username is not defined in Javascript and show me how to fix it.

Solution:

let username = "Janani";
console.log(username);
Enter fullscreen mode Exit fullscreen mode

Error2:

TypeError

const user = null;
console.log(user.name);
Enter fullscreen mode Exit fullscreen mode

Output:

TypeError: Cannot _read_ properties of null (reading _'name'_)
Enter fullscreen mode Exit fullscreen mode

Prompt to ChatGPT:
Explain this TypeError in simple words and provide the correct code.

Solution:

const user = null;
if(user) {
   console.log(user.name);
}
Enter fullscreen mode Exit fullscreen mode

Error3:

SyntaxError

if (true {
  console.log("Hello");
})
Enter fullscreen mode Exit fullscreen mode

Output:

SyntaxError: Unexpected token '{'
Enter fullscreen mode Exit fullscreen mode

Prompt to ChatGPT:
Find the syntax error in this code and explain it like I'm a beginner.

Solution:

if(true) {
  console.log("Hello");
}
Enter fullscreen mode Exit fullscreen mode

Error4:

Undefined

let age;
console.log(age);
Enter fullscreen mode Exit fullscreen mode

Output:

undefined
Enter fullscreen mode Exit fullscreen mode

Prompt to ChatGPT:
Why is this variable undefined? Explain with an example.

Solution:

let age = 25;
console.log(age);
Enter fullscreen mode Exit fullscreen mode

Error5:

NaN

let result = "Hello"*5;
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

NaN
Enter fullscreen mode Exit fullscreen mode

Prompt to ChatGPT:
Why am I getting NaN? How can I avoid it?

Solution:

let result = 10*5;
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Tips for Better AI Prompts

Instead of asking:

My code is not working.

Ask:

I'm getting TypeError: Cannot read properties of undefined. Here's my code. Explain the error in simple words and provide a corrected version.

The more context you give, the more accurate the AI's answer is likely to be.

Conclusion:

AI doesn't just fix your code-it can help you understand why an error happened. Use it as a learning partner rather than simply copying the solution. Over time, you'll become much better at debugging on your own.

Top comments (0)