Start learning free

LESSON 6 OF 410 · WELCOME TO JAVASCRIPT

Name Errors in JavaScript

Lesson Read the full explanation

TL ; DR:

  • A NameError occurs when JavaScript sees a word it does not recognize. Some examples:

  • Misspelling a function name:

    console.lg("Heyooo!"); // NameError: name 'console.lg' is not defined
    

  • Misspelling a variable name:

    let animal = "parrot";
    console.log(anmal); // NameError: name 'anmal' is not defined
    

  • When JavaScript encounters a name error, it immediately stops executing your code and throws a NameError instead.




Full lesson:

Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand and explain mistakes made in their programs.

Here are two common errors that we encounter while writing JavaScript code:


The SyntaxError:

Syntax errors are mistakes in the use of the JavaScript language, and are analogous to spelling or grammar mistakes in a language like English. For example, the sentence "Would you some tea?" does not make sense – it is missing a verb.

SyntaxError means there is something wrong with the way your program is written. Some examples:

1. Misuse of commas when declaring a string:

let greeting = 'Hey there!";

When we run this code we'll get a SyntaxError: Invalid or unexpected token.

2. Leaving out a parantheses:

console.log"My name is Andy");

When we run this code we'll get a SyntaxError: Unexpected string.


The ReferenceError:

A ReferenceError occurs when the JavaScript interpreter sees a word it does not recognize. Some examples:

1. Misspelling a class / function name:

consle.log("My name is Andy");

When we run this code we'll get a ReferenceError: consle is not defined.

2. Using a non-existent variable / Misspelling a variable's name:

let animal = "parrot";
console.log(aniimal);

When we run this code we'll get a ReferenceError: aniimal is not defined.


Assignment
Follow the Coding Tutorial and let's practice with errors!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · WELCOME TO JAVASCRIPT

    Name Errors in JavaScript, explained

    Introduction

    In this lesson, we will explore common errors in JavaScript, specifically NameError, SyntaxError, and ReferenceError. Understanding these errors is crucial for debugging and writing clean, efficient code. These errors often occur due to simple mistakes like typos, but they can halt the execution of your program, making it essential to identify and fix them promptly.

    Understanding the Basics

    Before diving into the specifics, let's understand the fundamental concepts:

    • NameError: Occurs when JavaScript encounters an unrecognized word, often due to typos in function or variable names.
    • SyntaxError: Happens when there is a mistake in the code's syntax, similar to grammatical errors in human languages.
    • ReferenceError: Triggered when the code references a variable or function that hasn't been declared or is misspelled.

    Grasping these basics is essential as they form the foundation for identifying and resolving errors in your code.

    Main Concepts

    Let's delve deeper into each error type with examples:

    NameError

    A NameError occurs when JavaScript encounters an unrecognized word. This often happens due to typos in function or variable names.

    // Example of NameError due to misspelled function name
    console.lg("Heyooo!"); // NameError: name 'console.lg' is not defined
    
    // Example of NameError due to misspelled variable name
    let animal = "parrot";
    console.log(anmal); // NameError: name 'anmal' is not defined
    

    SyntaxError

    A SyntaxError indicates a mistake in the code's syntax. It's akin to grammatical errors in human languages.

    // Example of SyntaxError due to misuse of quotes
    let greeting = 'Hey there!";
    
    // Example of SyntaxError due to missing parentheses
    console.log"My name is Andy");
    

    ReferenceError

    A ReferenceError occurs when the code references a variable or function that hasn't been declared or is misspelled.

    // Example of ReferenceError due to misspelled function name
    consle.log("My name is Andy");
    
    // Example of ReferenceError due to misspelled variable name
    let animal = "parrot";
    console.log(aniimal);
    

    Examples and Use Cases

    Let's look at some practical examples and use cases:

    // Correcting a NameError
    let animal = "parrot";
    console.log(animal); // Corrected: logs "parrot" to the console
    
    // Correcting a SyntaxError
    let greeting = "Hey there!";
    console.log(greeting); // Corrected: logs "Hey there!" to the console
    
    // Correcting a ReferenceError
    console.log("My name is Andy"); // Corrected: logs "My name is Andy" to the console
    

    Common Pitfalls and Best Practices

    Here are some common pitfalls to avoid and best practices to follow:

    • Double-check spellings: Always double-check the spellings of your function and variable names.
    • Use meaningful names: Use meaningful and descriptive names for variables and functions to reduce the likelihood of typos.
    • Consistent syntax: Follow consistent syntax rules to avoid syntax errors.
    • Code reviews: Regularly review your code or have someone else review it to catch errors you might have missed.

    Advanced Techniques

    For advanced error handling, consider using try-catch blocks to gracefully handle errors and provide meaningful feedback to users.

    // Example of using try-catch for error handling
    try {
      console.log(animal);
    } catch (error) {
      console.error("An error occurred: ", error.message);
    }
    

    Code Implementation

    Here is a well-commented code snippet demonstrating the correct use of the discussed concepts:

    // Correct implementation without errors
    let animal = "parrot"; // Declare a variable
    console.log(animal); // Log the variable to the console
    
    // Correct function call
    function greet() {
      console.log("Hello, world!");
    }
    greet(); // Call the function
    

    Debugging and Testing

    Debugging and testing are crucial for ensuring your code runs smoothly. Here are some tips:

    • Use console.log: Use console.log statements to track variable values and program flow.
    • Write tests: Write tests for your functions to ensure they work as expected.
    • Use debugging tools: Utilize debugging tools available in your development environment.
    // Example of a simple test case
    function add(a, b) {
      return a + b;
    }
    
    // Test the add function
    console.assert(add(2, 3) === 5, "Test failed: 2 + 3 should equal 5");
    

    Thinking and Problem-Solving Tips

    Here are some strategies for approaching problems related to these errors:

    • Break down the problem: Break down complex problems into smaller, manageable parts.
    • Practice regularly: Regular practice helps in identifying and fixing errors quickly.
    • Use coding exercises: Engage in coding exercises and projects to improve your skills.

    Conclusion

    In this lesson, we covered common errors in JavaScript, including NameError, SyntaxError, and ReferenceError. Understanding these errors is crucial for writing clean, efficient code. By following best practices and regularly practicing, you can minimize these errors and become a more proficient programmer.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free