Plenty of π
Module 6: Errors, Debugging, and Troubleshooting
Syntax vs. Runtime vs. Logical Errors

Understanding different types of errors is key to effective debugging.

  1. Syntax Errors:

    • Occur when your code violates the grammatical rules of JavaScript.
    • The JavaScript engine cannot parse or understand the code.
    • These errors are usually caught before the code even starts running (during the parsing phase).
    • Examples: Missing parentheses, misspelled keywords, incorrect operator usage.
    // let x = 5; // Correct
    // lt x = 5;  // SyntaxError: Unexpected identifier (misspelled 'let')
    // console.log("Hello); // SyntaxError: Invalid or unexpected token (missing closing quote)
    
  2. Runtime Errors (Exceptions):

    • Occur while the script is executing, after successful parsing.
    • Happen when the engine encounters an operation that it cannot perform.
    • Examples: Trying to call a method on an undefined variable, dividing by zero (though JS returns Infinity), accessing a property of null.
    let user = null;
    // console.log(user.name); // TypeError: Cannot read properties of null (reading 'name')
    
    let y;
    // y.toUpperCase(); // TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    
  3. Logical Errors:

    • The code is syntactically correct and runs without crashing, but it does not produce the intended or expected result.
    • These are often the hardest to find because the JavaScript engine doesn't report them as errors.
    • Requires careful testing, debugging, and understanding of the problem domain to identify.
    // Intention: Calculate average of two numbers
    let num1 = 10;
    let num2 = 5;
    let average = num1 + num2 / 2; // Logical error: division happens before addition due to precedence
    console.log(average); // Output: 12.5 (Expected: 7.5 if (num1+num2)/2 )