Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 6

Debugging JavaScript Syntax Errors

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! Welcome to our sixth lesson in the JavaScript Fundamentals module.

In our last lesson, you wrote and executed your first JavaScript programs using console.log(). You learned how to send messages, numbers, and the results of calculations to the browser console and the Node.js terminal. This was all about getting feedback when your code works correctly.

Today, we'll explore what happens when your code is not correct. This is a completely normal and frequent part of programming. Your goal for this lesson is to learn how to identify and fix basic syntax errors in JavaScript code. The console, which you've used for output, is also the primary tool that tells you when something has gone wrong. Mastering this skill will make you a more confident and effective programmer.

What are Errors in Programming?

Computers are incredibly powerful, but they are also incredibly literal. They follow instructions precisely as they are written. If an instruction is misspelled, incomplete, or violates the language's rules, the computer can't understand it.

To start, let's watch a short video that explains why this precision is so important and introduces the idea of errors as a natural part of programming.

Errors in JavaScript / Intro to JavaScript ES6 programming, lesson 6

This clip from 'Errors in JavaScript' by Codexpanse with Rakhim gives a great high-level view on why errors occur and why learning to deal with them is an essential skill for any developer.

Please watch from 00:58 to 01:51. Pay attention to the core message: making mistakes is guaranteed, and what matters is how you deal with them.

As the video states, dealing with errors is a fundamental part of a programmer's job. Let's learn about the different kinds of errors you'll encounter.


The Main Types of Errors

While there are many specific error messages, most problems you'll face as a beginner fall into a few main categories. It's very helpful to understand the difference between them.

Errors in JavaScript / Intro to JavaScript ES6 programming, lesson 6

The same video provides a clear, concise breakdown of the three most common error types you'll see in your console: Syntax, Reference, and Type errors. Understanding these categories will help you decipher error messages much faster.

Watch from 01:51 to 05:07. For each error type, focus on: The name of the error (SyntaxError, ReferenceError, TypeError). The simple explanation for what causes it. The analogy used to describe it (e.g., shouting nonsense, calling by a wrong name).

Let's summarize those key error types:

  1. Syntax Errors: These are like grammatical mistakes. You've broken the fundamental rules of the JavaScript language, and the interpreter cannot even begin to parse or run your code. This could be a missing parenthesis, an extra quote, or a misspelled keyword.
  2. Reference Errors: This happens when you try to use a variable or function that hasn't been defined or is not accessible in the current context. It's like asking for someone by the wrong name—they don't exist in that room.
  3. Type Errors: This occurs when you try to perform an operation on a value of the wrong type. For example, trying to treat a number like it's a function (as in the video) or trying to read a property from a value that isn't an object.

Today, our main focus is on syntax errors, but you'll see the other types appear as we start debugging.


A Practical Debugging Exercise

The best way to learn debugging is by doing it. We're going to intentionally break some code and then fix it together.

  1. Open your script.js file in VS Code.
  2. Delete any old code from the previous lesson.
  3. Copy and paste the following broken code block into your file:
// This code has several errors!
const GREETING = "Hello"
const TOPIC = 'Debugging'

console.log(GREETING, 'and welcome to the world of' TOPIC);

console.log(username);

GREETING.toUpperCase;

Now, save the file, open index.html in your browser, and open the developer console. You'll see an error message. Let's fix these errors one by one.

Fixing Error #1: The SyntaxError

The first error you see in the console should look something like this:

Uncaught SyntaxError: missing ) after argument list (or similar)

This error message is your best friend. It tells you three things:

  • Error Type: SyntaxError. The code violates JavaScript's grammar.
  • Error Message: missing ) after argument list. A helpful clue about what's wrong.
  • Location: It will point to a file name and line number (e.g., script.js:5). This tells you exactly where the engine first encountered the problem.

The problem is on this line:
console.log(GREETING, 'and welcome to the world of' TOPIC);

Looking closely, we can see that we are trying to log three things: the variable GREETING, the string 'and welcome...', and the variable TOPIC. As we learned in the last lesson, when you give console.log() multiple items, they must be separated by commas.

The Fix: Add a comma between the string and the TOPIC variable.

// FIX #1: Add a comma
console.log(GREETING, 'and welcome to the world of', TOPIC);

Save your file and refresh the browser. The first error is gone, but now a new one has appeared! This is the process of debugging: fix one error, then move to the next.

Fixing Error #2: The ReferenceError

The new error should be:

Uncaught ReferenceError: username is not defined

  • Error Type: ReferenceError. We're trying to use something that doesn't exist.
  • Error Message: username is not defined. JavaScript is telling you it has no idea what username is.
  • Location: It will point to the line console.log(username);.

This is a classic ReferenceError. We never created a variable called username. Perhaps we meant to use one of our existing variables, like TOPIC?

The Fix: Let's change this line to log something that actually exists. We'll change username to TOPIC.

// FIX #2: Use a defined variable
console.log(TOPIC);

Save and refresh again. One more error to go!

Fixing Error #3: The TypeError (A Sneaky One!)

This time, you won't see an error in the console. The code runs without crashing. But did it do what we expected?

The line in question is:
GREETING.toUpperCase;

toUpperCase is a built-in method that should return a new string in all capital letters. We might expect to see "HELLO" in the console, but nothing appears. This is an example of a logic error. The syntax is valid, so JavaScript doesn't complain, but the code doesn't produce the intended result.

The problem is that toUpperCase is a function (or more accurately, a method). To execute a function, you must use parentheses (). By just writing GREETING.toUpperCase, we are only referencing the function itself, not running it. Furthermore, running it won't automatically print it. We need to wrap it in console.log().

The Fix: Add parentheses to call the function and wrap the entire expression in console.log() to see the result.

// FIX #3: Call the function with () and log the result
console.log(GREETING.toUpperCase());

After making this final fix, your script.js file should look like this:

// This code is now fixed!
const GREETING = "Hello";
const TOPIC = 'Debugging';

console.log(GREETING, 'and welcome to the world of', TOPIC);

console.log(TOPIC);

console.log(GREETING.toUpperCase());

Save and refresh one last time. Your console should now show three lines of output with no errors. Great job!

Test your understanding!

What type of error would you get from the following line of code and why?
let my-variable = 10;

Show answer

You would get a SyntaxError. Variable names in JavaScript cannot contain a hyphen (-). The JavaScript engine sees the - as a subtraction operator and gets confused because the expression doesn't form a valid statement. This breaks the grammatical rules of the language.


Tools and Best Practices to Avoid Errors

While you can't avoid errors completely, you can use tools and habits to catch them early.

1. Trust Your Code Editor

Modern editors like VS Code have built-in intelligence to spot errors as you type. You've likely already seen red squiggly lines under your code. This is your first line of defense!

This next video demonstrates how VS Code and the browser console work together to help you debug.

Best Debugging Tips For Beginners

In 'Best Debugging Tips For Beginners,' Web Dev Simplified shows how to leverage your editor's built-in hints to find syntax errors before you even run the code.

Watch from 00:36 to 02:49. Notice how the instructor hovers over the red squiggly lines in VS Code to get a description of the error, often providing a clearer clue than the browser console's message.

2. Develop Good Habits

Writing clean, readable code helps prevent errors. The article "Understanding Syntax and Code Structure in JavaScript" from DigitalOcean provides excellent guidance on this.

Understanding Syntax and Code Structure in JavaScript

This article discusses several conventions that, while not always mandatory for the code to run, make your code much easier to read and debug for both yourself and others.

Please read the sections on Semicolons, Indentation, and Identifiers. Pay special attention to: When semicolons are optional versus required. Why indentation is crucial for readability. The rules for naming variables (identifiers), especially regarding reserved keywords.

Here's a visual summary of common syntax issues related to variables.

Deep Dive: Syntax Errors in Variable Expression
This image highlights four common errors: missing semicolons, using invalid characters in names, not respecting case-sensitivity, and creating overly long names.

Conclusion

You've taken a huge step forward today. Learning to read error messages and debug code is one of the most empowering skills a developer can have. Instead of being a source of frustration, an error message is now a helpful clue pointing you toward a solution.

Key Takeaways:

  • Errors are a normal and expected part of programming. Debugging is a core skill.
  • The three most common error types for beginners are SyntaxError (broken grammar), ReferenceError (variable doesn't exist), and TypeError (using a value incorrectly).
  • Always read the error message carefully in the console. It gives you the error type, a message, and the line number.
  • Fix errors one at a time, starting from the top. Refreshing your code after each fix will reveal the next error in the sequence.
  • Leverage your tools! VS Code's error highlighting is your first clue that something is wrong.

In our next lesson, we will begin a new module and dive deep into one of the most fundamental concepts in all of programming: variables. You will learn how variables work to reserve space in computer memory and store the data your programs need to function.