Reading and Repairing an Error
Introduction
Welcome back to Writing and Running Your First JavaScript Programs! We have printed messages and left ourselves tidy notes. Now we tackle something every programmer meets, usually within the first ten minutes: the error message.
So far our programs have run cleanly, but we have probably already noticed how picky JavaScript is. One missing quotation mark and the whole thing stops. That is not a sign of failure; it is a conversation. JavaScript is telling us exactly what confused it and where.
In this lesson, we will learn how to:
- Read an error message and find the line number it points at.
- Recognise the three mistakes we are most likely to make right now.
- Follow a simple routine to repair the line and run again.
By the end, an error will feel less like a wall and more like a signpost.
Errors Are Normal
Let's start with the most important idea in this lesson: errors are a normal part of programming. Experienced programmers see them many times a day. The difference between a beginner and an expert is not that the expert never causes errors; it is that the expert reads the message, fixes the line, and moves on without a second thought.
Because JavaScript reads our code so literally, a tiny slip is enough to stop it. The good news is that it never stops silently. It reports what confused it and the line where it noticed - which is usually, though not always, the line with the mistake.
Anatomy of an Error Message
Here is a program with a mistake in it. The second line is missing its closing quotation mark:
When we click Run, instead of two messages we get this:
Let's read it from the top, because every part is useful:
- The first line names the file, and after the colon, the line number where JavaScript got confused: line 2.
- The second line shows us that line of code, so we do not even have to go looking for it.
- The carets
^^^point at the part of the line where JavaScript noticed the trouble - usually the mistake itself, sometimes the first thing after it. - The last line names the kind of error and gives a short description.
SyntaxErrormeans "this is not valid JavaScript". The description,Invalid or unexpected token, is JavaScript's way of saying it hit something it could not make sense of.
This is what Node.js prints; the exact wording varies a little between versions, but the shape is usually the same: file and line number first, the offending code, then the error name. The line number is the part to look at first.
Notice one more thing: Order received. did not print, even though that line was fine. A SyntaxError is found before the program starts running, so nothing runs at all. Repairing line 2 brings line 1 back too.
