JavaScript is a widely used programming language for creating interactive and dynamic web pages. However, errors are an inevitable part of coding. This documentation aims to provide a simple guide for users to understand common JavaScript errors and how to troubleshoot them.

What are JavaScript errors?

JavaScript errors are problems or bugs in JavaScript code that occur during the execution of a script in a web browser or any JavaScript environment. These errors can disrupt the normal flow of a program, leading to unexpected behavior or failure of certain functionalities on a website or application.

Capturly’s JavaScript Error Tracking feature collects these errors from your website automatically. With the integration of session recordings, you can replay those user sessions where errors occurred.

What are the common JavaScript errors?

  • Uncaught: Indicates that the error was not handled by your code.
  • SyntaxError: Specifies that there is a mistake in the code structure.
  • TypeError: Indicates that an operation is performed on a value of the wrong type.
  • Unexpected token: Points to the specific part of the code causing the issue.
  • Invalid array length: Specifies the nature of the error, indicating that the attempted operation involves an invalid array length.
  • Cannot read property ‘property_name’ of null: Specifies that the attempted operation involves accessing a property on a null value.

CORS errors are detected in Capturly. What does it mean?

Capturly may encounter difficulties capturing error messages when they originate from scripts with different origins. This issue is commonly known as a CORS (Cross-Origin Resource Sharing) error, and it arises due to security restrictions on cross-origin requests.

When your webpage encounters a CORS error, you’ll receive the following message:

“Unfortunately, due to security restrictions imposed by browser policies, we are unable to provide you with specific details about some errors, as they appear to be originating from a different domain (cross-origin). This prevents us from accessing the necessary error details. Please check out our documentation page for more information.”
CORS (Cross-Origin Resource Sharing) error message in Capturly under the JavaScript error page

To address CORS issues, consider the following solutions:

 1. Add crossorigin attribute to your script tags 

Include the `crossorigin=”anonymous”` attribute in your script tags to enhance compatibility and allow the browser to make cross-origin requests without sending credentials.

<script src="https://othersite.com/script.js" crossorigin="anonymous"></script>
 2. Server-Side Configuration 

Configure your server to include the appropriate CORS headers in its responses. The most permissive option is to allow all origins:

Access-Control-Allow-Origin: *

Note: If your script comes from a CDN source, it likely already includes the necessary CORS headers in its response.

What is a SyntaxError?

SyntaxError is like grammatical mistakes in a programming language. Just as using wrong grammar makes a sentence unclear or incorrect in English, syntax errors occur when code is written in a way that the computer can’t understand. It’s like missing punctuation or jumbling words in a sentence, which makes it confusing or wrong for the computer.

Technical definition: Syntax errors in programming are mistakes in the code’s structure, violating the grammatical rules of the programming language. In JavaScript, this might include missing semicolons, unclosed braces, misplaced parentheses, or incorrect use of language constructs, leading to failure in code execution.

Example

javascript
// Incorrect syntax
let x = 10;
if x === 10 {
  console.log("x is 10");
}

// Correct syntax
let x = 10;
if(x === 10){
  console.log("x is 10");
}

Potential effects on user experience

Syntax errors in the frontend code can lead to various negative effects on user experience, including:

  • Non-functional web pages: The webpage might not load properly or at all, leading to a blank or incomplete display.
  • Broken interactivity: Interactive elements like buttons, links, and forms may not work, frustrating users who expect certain actions.
  • Layout issues: The visual layout might appear broken or disorganized, affecting the aesthetic appeal and usability.
  • Inaccessibility: Key functionality might become inaccessible, hindering users’ ability to navigate or use the website effectively.

These issues can cause user frustration, diminish trust in the website, and potentially lead to users leaving the site.

Troubleshooting tips

  • Refer to the official documentation: JavaScript has comprehensive documentation available online. Websites like MDN Web Docs (Mozilla Developer Network) provide detailed information about JavaScript syntax, functions, and features.
  • Check syntax rules: Familiarize yourself with basic JavaScript syntax rules, such as proper placement of semicolons, curly braces, parentheses, and keywords.
  • Learn from examples: The documentation often includes examples that illustrate correct syntax. Analyze these examples to gain insights into how different language constructs should be used.
  • Use developer tools: Modern web browsers come with built-in developer tools that can help identify syntax errors in your code. The console tab often provides information about the specific syntax error and its location.

What is a ReferenceError?

Imagine trying to call a friend whose phone number you don’t have. In programming, a Reference Error is similar—it happens when the program tries to use something (like a variable or function) that it doesn’t know or can’t find. This usually occurs because it hasn’t been properly set up or is misspelled.

Technical definition: Reference errors occur when the code attempts to use a variable or function that has not been defined, often leading to a message stating that an object is ‘undefined’ or ‘null’.

Example

javascript
// Trying to use an undefined variable
console.log(nonExistentVariable);

Potential effects on user experience

Reference errors in a web application can negatively impact user experience in several ways:

  • Functional breakdown: Critical functionality might not work, leading to features like buttons, forms, or navigation elements becoming non-responsive.
  • Incomplete or broken content: Web pages may fail to load completely or correctly, resulting in missing content or layout issues.
  • Error messages: Users might encounter error messages or alerts, leading to confusion and a lack of understanding of what went wrong.
  • Reduced trust and credibility: Frequent errors can diminish users’ trust in the reliability and professionalism of the website or application.
  • Frustration and disengagement: Such issues can frustrate users, potentially causing them to leave the site and negatively affecting overall engagement and satisfaction.

Troubleshooting tips

  • Double-check definitions: Ensure all variables and functions are declared before they are used. This includes checking for any missed var, let, or const statements.
  • Verify scope: Variables and functions have different scopes (global or local). Verify that the variable or function is accessible in the scope where it’s being used.
  • Naming consistency: Ensure that variable and function names are consistent throughout the code. Pay attention to case sensitivity in JavaScript, as it distinguishes between myVariable and MyVariable.
  • Check for typos: A common cause of reference errors is misspelling variable or function names. Double-check for any typographical errors in your code.

What is a TypeError?

Imagine trying to use a hairdryer to make toast. Just like the hairdryer isn’t designed for toasting bread, in computer programming, a Type Error happens when you try to do something with a piece of data that doesn’t make sense for its type. For example, if you treat a number as if it were a piece of text (like trying to capitalize the number 5), the computer gets confused because the action doesn’t fit the data type. This mismatch leads to a “type error.” It’s like a miscommunication where the computer expects one kind of data but gets something else instead.

Technical definition: Type errors occur when operations are attempted on a value of an incompatible type, like trying to execute a string method on a number. This is common in JavaScript due to its dynamic typing.

Example

Example:
javascript
let numberValue = 5;
let result = numberValue.toUpperCase(); // Type Error: numberValue.toUpperCase is not a function

Potential effects on user experience

Reference errors in a web application can significantly affect the user experience in various ways:

  • Malfunctioning features: Essential features may not function as intended, causing frustration and confusion.
  • Broken interactivity: Interactive elements like buttons, links, or forms might become unresponsive.
  • Partial or incomplete page loading: Web pages may fail to load fully or display correctly.
  • Unexpected behavior: Users might encounter erratic or unpredictable behavior in the application.
  • Error messages: Display of technical error messages, which can be confusing and uninformative for the end-user.

These issues can lead to user dissatisfaction, decreased trust in the application, and a higher likelihood of users abandoning the site.

Troubleshooting tips

  • Review variable names: Double-check the names of the variables you are using. Ensure consistency in spelling and case sensitivity.
  • Be mindful of typos: Typos are a common source of reference errors. Pay attention to your code and look out for small spelling mistakes that might lead to undefined variables.
  • Use descriptive names: Employ meaningful and descriptive variable names. This not only reduces the chances of typos but also enhances code readability.

What is a RangeError?

Imagine you have a set of boxes that can each hold a certain number of items. A Range Error in programming is like trying to put more items in a box than it can hold, or maybe even trying to have a negative number of items. In computers, this error occurs when a program tries to handle a number or amount that is too big, too small, or just doesn’t make sense within its rules. It’s like overloading or underloading based on set limits.

Technical definition: RangeError occurs when a numeric value is outside the valid range. This typically occurs when executing a function or operation that has predefined constraints on the acceptable range of input values. For instance, instantiating an array with a length that is not a positive integer, or when arithmetic operations result in a value that exceeds the representable range of the JavaScript number type, would trigger this error.

Example

javascript
let arr = new Array(-1); // RangeError: Invalid array length

Potential effects on user experience

Range errors in user experience can lead to several issues:

  • Crashes and freezes: The application may crash or freeze if it encounters a range error, leading to a complete halt in user interaction.
  • Incorrect or incomplete functionality: Functions that rely on numerical values might behave incorrectly or fail to complete their tasks.
  • Unexpected behavior: Users might experience erratic or unpredictable behavior from the application, leading to confusion.
  • Error messages: Users could be confronted with error messages, which might be confusing if not clearly explained.
  • Loss of user data or progress: In some cases, a range error might result in the loss of user-entered data or progress within the application.

Overall, range errors can significantly disrupt the user’s interaction with the application, leading to a poor experience.

Troubleshooting tips

  • Validate input ranges: Before performing operations that involve numeric values, ensure that the values fall within a valid range. Check for edge cases and unexpected input.
  • Use conditional statements: Implement conditional statements to check if numeric values are within acceptable ranges before using them in operations or calculations.
  • Error handling: Use try-catch blocks in your code to handle potential range errors gracefully and provide informative feedback to users.