By the end of this lesson you will be able to
- Tell a syntax error, a runtime error and a logic error apart.
- Read an error message and find the type of problem and the line it points to.
- Follow a repeatable debugging method: reproduce, narrow down, fix and test.
- Use `console.log` to look at what a variable holds while a program runs.
- Compare broken code with fixed code and explain what changed and why.
Every programmer, from a beginner to an expert, writes code that does not work the first time. Errors are not a sign that you are bad at this. They are normal, and the computer is usually trying to tell you exactly what is wrong. Learning to read those messages calmly, and to hunt for a problem in a methodical way instead of guessing, turns frustration into a skill you will use in every later lesson.
What is a bug?
A Bug is a mistake in a program that makes it behave in a way its author did not intend. Debugging is the work of finding and fixing bugs. The word bug is old engineering slang for a fault, and it has stuck. A bug is almost never caused by the computer being "stubborn". The computer did exactly what the code said. The code said the wrong thing.
Bugs fall into three groups. Knowing which group you are facing tells you where to look first.
| Kind | What goes wrong | How it shows up | Example |
|---|---|---|---|
| Syntax error | The code breaks the spelling and punctuation rules of the language | The program will not start; an error message appears at once | A missing closing bracket |
| Runtime error | The code is valid but fails while running | The program starts, then stops with an error message | Using a variable that was never created |
| Logic error | The code runs without complaint but gives the wrong answer | No message at all; the result is simply wrong | Using + where you meant * |
- Rule of the language broken
- Message appears at once
Easiest to find.
- Valid code that fails
- Program stops with a message
Medium difficulty.
- Runs but gives a wrong answer
- No message at all
Hardest to find.
Read this figure as text
Three columns showing syntax error, runtime error and logic error with when each is noticed.
Syntax error: noticed before the program runs, the computer shows a message, easiest to find. Runtime error: noticed while the program runs, the program stops with a message, medium difficulty. Logic error: never noticed by the computer, the program finishes but gives a wrong answer, hardest to find because there is no message.
Reading an error message
An Error message looks scary but follows a pattern: the kind of error, a short description and usually a place (a file name and a line number). Read it from left to right and ignore the rest at first. In a browser you see these messages in the developer tools console, which a later lesson explores fully. Here is a simulated console showing a typical one.
Uncaught ReferenceError: total is not defined
at script.js:3
- Marker 1: Kind and description: a name was used that does not exist
- Marker 2: Place: file script.js, line 3
Read this figure as text
A simulated console window with a red error message pointing to line 3 of a script file.
A browser-style window titled Console. The first line, marked 1, reads: Uncaught ReferenceError: total is not defined. The second line, marked 2, reads: at script.js:3 which gives the file name and line number. Marker 1 is the kind and description of the error. Marker 2 is the place where it happened.
Here the message says a ReferenceError: the code used the name total, but no variable with that name exists. It happened at line 3 of script.js. Often the real mistake is on that line or just before it. For a missing bracket, the computer can only notice the problem when it reaches something unexpected, so check the line above as well.
| Message | Usual meaning | First thing to check |
|---|---|---|
Uncaught SyntaxError: Unexpected token | A symbol is where the language does not expect it | Missing or extra bracket, quote or comma on this or the previous line |
ReferenceError: x is not defined | A name was used that was never created | Spelling and capital letters; is the let line above? |
TypeError: Cannot read properties of undefined | Asking for something inside a value that does not exist | Print the value before the failing line |
SyntaxError: missing ) after argument list | A closing round bracket is missing | Count the brackets and quotes on the line |
A method for debugging
Guessing and changing things at random makes bugs worse. Use the same method every time. It is slow for the first few bugs and fast ever after.
- ReproduceMake it happen on purpose
- Narrow downFind the smallest cause
- Change one thingNever several at once
- TestBug gone? Nothing else broken?
Read this figure as text
A cycle of four steps for finding and fixing bugs.
A cycle of four stages that repeats until the bug is gone. 1: Reproduce, make the problem happen on purpose and note exactly what you did and saw. 2: Narrow down, find the smallest part of the code that causes it. 3: Change one thing, fix the likely cause and change only that. 4: Test, run again and check both the bug and everything that used to work.
The tool that makes narrowing down easy is console.log. It prints the value of anything you choose, at the moment the line runs, so you can compare what you expected with what actually happened. Add it, run, read, then remove it when you are done.
A worked example: before and after
Wanjiru writes a small program that works out the total cost of 4 pencils at 25 shillings each. She expects 100 but sees 29 on the screen. The program ran with no error message at all, so this is a logic error. Here is her code.
let pencilPrice = 25;
let quantity = 4;
let total = pencilPrice + quantity;
console.log(total);Step one is to reproduce: the output is 29 every time. Step two is to narrow down. The only calculation is on line 3, so she adds console.log lines to check the inputs.
let pencilPrice = 25;
let quantity = 4;
console.log(pencilPrice, quantity); // prints 25 4 so the inputs are fine
let total = pencilPrice + quantity;
console.log(total); // prints 29Both inputs are correct, so the fault must be the calculation itself. She used + where she meant *. Step three: change that one thing. Step four: run again and check.
let pencilPrice = 25;
let quantity = 4;
let total = pencilPrice * quantity;
console.log(total);- total = pencilPrice + quantity
- 25 + 4
- Prints 29
Wrong: plus instead of times.
- total = pencilPrice * quantity
- 25 * 4
- Prints 100
Correct.
Read this figure as text
A before and after comparison of the pencil total code, with output 29 before and 100 after.
Before: total is pencilPrice plus quantity, which is 25 plus 4, so the program prints 29, which is wrong. The mistake is the plus sign. After: total is pencilPrice times quantity, which is 25 times 4, so the program prints 100, which is correct. Only one symbol changed.
Now a syntax error, which is easier. This code is missing a closing bracket on the second line, and the console reports SyntaxError: missing ) after argument list. Look at the brackets, not at the rest of the line.
let name = "Amina";
console.log("Hello, " + name;let name = "Amina";
console.log("Hello, " + name);Common mistakes
✖ Instead of: Panicking and changing many lines when an error appears.
✔ Do this: Read the message, find the line, and change one thing at a time so you know what worked.
✖ Instead of: Ignoring the error message and guessing.
✔ Do this: The message names the kind of error and usually the place. Read it first; it is the cheapest clue you will get.
✖ Instead of: Assuming that no error message means the program is correct.
✔ Do this: Logic errors give no message. Always test with an example where you already know the right answer.
If something goes wrong
- I fixed the line the message named but the same message appears again.
- The cause was probably earlier. Check the line above for a missing bracket, quote or comma, and check that every opening bracket has a closing one.
- console.log prints nothing.
- Open the browser's developer tools console (press F12 in most browsers) and make sure you are looking at the Console tab. Also check that the line with console.log actually runs, for example that it is not inside an if that is false.
- I fixed one error and now there is a different one.
- This is normal. The computer stops at the first problem it meets, so fixing it reveals the next. Keep repeating the cycle one error at a time.
Key terms
- Bug
- A mistake in a program that makes it behave in a way its maker did not intend.
- Debugging
- Finding and fixing mistakes in a program.
- Syntax error
- A mistake in the spelling or punctuation of code that stops the computer reading it at all.
- Logic error
- A mistake where the code runs without complaint but does the wrong thing.
- Error message
- A message from the computer or program that says something went wrong and often where and why.
Practise it for real
Reading is not the same as being able to do it. Complete these on your own computer, then tick only what you have actually done. These ticks are your own honest record: nothing checks them for you.
Name the kind of error
For each case, write whether it is a syntax error, a runtime error or a logic error, and which line you would check first. (a) The program will not start and the console says Unexpected token at line 5. (b) A shop program prints a total of 12 for 3 items at 5 shillings each, with no message. (c) The program runs for a moment and then stops with ReferenceError: discount is not defined. Write one sentence saying why you chose each.
Challenge: find the three bugs by reading
Here is a small program for a fictional bus fare. Read it carefully on paper and find and describe every problem, then write the corrected version. The code is: let adultFare = 80; then let passengers = 3; then let total = adultFare + passengers; then if (total > 200) { console.log("Too expensive" }. Do not run it. Use the method: say what you expect, find where the code differs, change one thing at a time.
Knowledge check
6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.
Summary
- Syntax errors break the language rules, runtime errors fail while running, and logic errors give wrong answers silently.
- An error message gives the kind, a description and usually a file and line number.
- The cause may be on the line before the one named.
- Debug by reproducing, narrowing down, changing one thing and testing again.
- console.log lets you look inside a program while it runs.
Checklist: can you do these?
Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).
Related lessons
References and further reading
Official sources for details that can change between versions.
- What went wrong? Troubleshooting JavaScript (MDN Web Docs)
- JavaScript error reference (MDN Web Docs)