Every programmer writes bugs. What separates beginners from experienced developers is not fewer mistakes but a calm method for finding them. This guide gives you a simple routine.
1. Read the error message
The message usually tells you the kind of problem and the line where it happened.
ReferenceError: x is not definedmeans you used a name that does not exist: a typo, or a variable used outside the place where it was created.TypeError: Cannot read properties of undefinedmeans you tried to use a value that is empty. Something you expected to exist does not.SyntaxErrormeans the code is written wrongly: a missing bracket, quote or comma.
2. Make the code easier to read
Messy indentation hides mistakes such as a missing brace. Paste the code into the JavaScript Formatter and read it again with clean structure.
3. Look at the values
Add console.log() lines to see what your variables really contain at each step.
console.log('price is', price, typeof price);
Very often the bug is that a value is not what you think: a string instead of a number, or undefined.
4. Shrink the problem
Remove or comment out code until the bug disappears, then put it back piece by piece. The last piece you added contains the problem. Test one small function at a time with simple inputs.
5. Check the usual suspects
- Off-by-one mistakes in loops, such as using
<=instead of<. - Comparing with
==when you meant===. - Forgetting that adding a string and a number joins them as text.
- Changing a list while you loop over it.
- Asynchronous code: a value is used before it has arrived.
6. Explain it out loud
Describe what each line should do, one at a time. Often you find the mistake while explaining ("rubber duck debugging").
7. Ask for help the right way
If you are stuck, the AI Debugging Assistant can point out likely causes. Treat its answer as a hint and check it yourself.
Practise on purpose
Debugging is a skill you build with practice. Try our coding challenges: the debugging ones give you broken code with tests, so you can fix it and see the tests pass.