JavaScript: Errors

Error Message

Current learning: Odin JS Understanding Errors. Tips for resolving errors: 3. Chrome Debugger

Error messages parts:
  • Error type
    • ReferenceError: var is not defined.
  • Error location: file name, line number, and sometimes column number
    • at script.js:4
    • at script.js:4:13
  • Stack trace: trace the evolution of an error back to its origin.
    • Code:
      const a = 5;
      const b = 10;
      
      function add() {
          return c;
      }
      
      function print() {
          add();
      }
      
      print();
      
    • Error message:
      Uncaught ReferenceError: c is not defined       script.js:5
          at add (script.js:5)
          at print (script.js:9)
          at script.js:12
      

Error Types

Syntax Error
Thrown when code being run is not written correctly.
Examples:
  • Uncaught SyntaxError: Invalid or unexpected token
    function sayHi() {
        console.log "Hi"
    }
    
Reference Error
Thrown when code refers to a variable that is not declared and/or initialized within the current scope.
Examples:
  • ReferenceError: c is not defined.
    const a = 5;
    const b = 10;
    
    function add() {
        return c;
    }
    
    add();
    
  • ReferenceError: can't access lexical declaration 'X' before initialization.
Type Error
Thrown when:
  • An operand or argument passed to a function is incompatible with the type expected by the operator or function.
  • Attempting to modify a value that can't be changed.
  • Attempting to use a value in an inappropriate way.
Examples
  • TypeError: string1.push is not a function
    const string1 = "Hello ";
    const string2 = "Kitty!";
    const message = string1.push(string2);
    
    While .push() is a function, it's an array method, not a string method. The type is wrong. This will work just fine if we use the string method .concat()

Warning

Warnings
Informational message providing insight on potential problems that may not crash the program at runtime or at all.
Warnings vs errors
  • Should address warning asap, but not as significant as error. The program still can run (at least at current condition).
  • Warnings are typically shown in yellow, while error is in red. But this can be different depends on the platform.

Exercise


References