JavaScript: Syntax errors
If a JavaScript program is written in violation of the rules, the interpreter will stop execution and print an error message. This message indicates:
- the type of error,
- the line where it occurred,
- and (often) the point where the interpreter "stumbled."
What is a syntax error?
A syntax error (SyntaxError) is a violation of the rules for writing code (grammar rules) in a particular programming language. Such errors occur when code is written with a deviation from the expected format: an unclosed string, a missing bracket, a wrong order of symbols, and so on.
Unlike natural languages, where text with mistakes can be understood from context, in programming even the slightest deviation makes the code unusable.
Code with an error Interpreter Result
┌────────────────────┐ ┌───────────┐ ┌──────────────────────┐
│ console.log('Hi' │──→│JavaScript │──→│ SyntaxError: │
└────────────────────┘ └───────────┘ │ missing ) after args │
└──────────────────────┘Let's look at a simple example with a syntax error:
// The correct version is: console.log('Hodor')
console.log('Hodor'In this code the bracket is not closed, which makes the program incorrect from the syntax point of view. Let's try to run the program, and the interpreter will produce an error:
node index.js
index.js:2
console.log('Hodor'
^
SyntaxError: missing ) after argument listThe text may be unclear at first, but that's normal — the more often you encounter such errors, the faster you'll learn to understand what happened.
Why are such errors considered simple?
Syntax errors:
- are easy to notice: the code is often highlighted in the editor;
- are easy to fix: it's enough to restore the missing symbol or correct the structure.
But there's a fly in the ointment. The interpreter doesn't always point exactly to the place where the error was made. Sometimes the problem is several lines above. For example, an opened but unclosed bracket on one line can "break" all the following code.
What to do with a syntax error?
- Read the error message. It almost always contains useful information.
- Check the line indicated in the message, and the line before it: sometimes the error is "hidden" a bit earlier.
- Use an editor with syntax highlighting: it will help you notice problems right away (for example, unclosed quotes or brackets).
Instructions
The program starts and reports the result. Write a program that prints:
Program started successfullyAfter the program works, deliberately break it — make one of the syntax errors:
- remove the closing quote;
- remove the closing bracket.
Run the code and read the JavaScript message. You will see such messages often — it's important to learn to read them. Then restore the working version so the exercise passes the check.
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('Program started successfully');
});Teacher's solution will be available in:
20:00
