By counting more than 1,000 items in our database, we found 10 of the most common errors in JavaScript. Here’s why these errors happen and how to prevent them.
The number of these errors is calculated from the data we collect. Rollbar collects all errors in each project, summarizes the number of times each error occurred, and then groups the errors by their characteristics.
Here are the top 10 most common JavaScript errors:
Let’s dive into the circumstances under which each error occurs to determine what causes it and how to avoid it.
1. Uncaught TypeError: Cannot Read Property
This is the most common error encountered by JavaScript developers. Chrome displays this error when you read a property or call a method on an undefined object.
This error can occur for a number of reasons, but a common one is incorrectly initializing state when rendering UI components. Let’s look at an example of this happening in a real application.
The above code has two important aspects:
One is the state of the component (such as this.state), which is undefined before the lifecycle begins.
The second is that when retrieving data asynchronously, either in the constructor componentWillMount or extracting componentDidMount from the constructor, the component is rendered at least once before the data is loaded. When detecting the first render, you will find that this.state.items is undefined. Uncaught TypeError: Cannot read property ‘map’ of undefined” in the consol “.
The solution is simple: initialize the state with reasonable defaults in the constructor.
2. TypeError: ‘undefined’ Is Not an Object (evaluating…)
This is an error that occurs when reading a property or calling a method on an undefined object in Safari, which is essentially the same error as in Chrome, except Safari uses a different error message.
3. TypeError: Null Is Not an Object (evaluating…)
This is an error that occurs when reading a property or calling a method on an empty object in Safari.
Interestingly, null and undefined are two different types in JavaScript, which is why two different error messages appear. Undefined is usually an unassigned variable, and null indicates that the value is null. To verify that they are not equal, use the strict equality operator:
In a practical case, one of the causes of this error is trying to use DOM elements in JavaScript before they are loaded. This is because the DOM API returns NULL for blank object references.
Any JS code that executes and processes A DOM element should be executed after the DOM element is created. The JS code is interpreted top-down as specified in HTML. Therefore, if the tag exists before the DOM element, the JS code inside the script tag is executed when the browser parses the HTML page. This error occurs if the DOM element has not been created before the script is loaded.
In this case, we can solve this problem by adding an event listener that will notify us when the page is ready. Once the addEventListener is triggered, the init() method can use DOM elements.
4. (unknown): Script Error
Scripting errors occur when uncaught JavaScript errors violate the boundary rule. For example, if JavaScript code is hosted on a CDN, any errors that are not caught (issued through the window.onerror handler, not caught in a try-catch) will only be reported as “script errors.” This is a browser security measure designed to prevent cross-domain transfer of data.
To get the actual error message, do the following:
Access-Control-Allow-Origin
Setting access-Control-allow-origin to * indicates that resources can be correctly accessed from any domain. * You can also use your own domain name if necessary, for example:
Access – Control – Allow – Origin: www.example.com.
Here are some examples of Settings in various environments:
Apache
In the JavaScript folder, create a.htaccess file with the following contents:
Nginx
Add the add_header directive to the location block that provides the JavaScript file:
HAProxy
Add the following to the static resource configuration back end that provides JavaScript files:
Set Crossorigin = “anonymous” on the script tag
In your HTML source, set access-Control-Allow-Origin for each SCRIPT, and in the set SCRIPT TAB, set Crossorigin =”anonymous”. Before adding the Crossorigin attribute to the script tag, make sure you are sending the header to the script file. In Firefox, if the Crossorigin attribute exists but the Access-Control-Allow-Origin title does not, the script will not execute.
TypeError: Object Doesn’t Support Property
This error occurs in IE when an undefined method is called.
This is equivalent to the Chrome error “undefined ‘is not a function”. Different browsers may have different error messages for the same logical error.
This is a common problem with JavaScript namespaces in Internet Explorer Web applications. Most of the reason for this is that IE cannot bind methods in the current namespace to the this keyword. For example, if you have the namespace isAwesome for the JS Rollbar method. In general, the isAwesome method can be called with the following syntax if it is inside the Rollbar namespace:
Chrome, Firefox, and Opera accept this syntax, but IE does not. Therefore, the safest thing to do when using a JS namespace is to always prefix it with the actual namespace.
TypeError: ‘undefined’ Is Not a Function
This error occurs in Chrome when an undefined function is called.
As JavaScript coding techniques and design patterns have become more complex over the past few years, the scope of self-references in callbacks and closures has increased, which is a major source of this confusion.
As shown in the following code snippet:
Executing the above code results in the following error: “Uncaught TypeError: undefined is not a function.” The above error occurs because when you call setTimeout(), you are actually calling window.settimeout (), and the anonymous function passed to setTimeout() is defined in the context of the window object, The window object does not have a clearBoard() method.
The solution that suited older browsers was to simply store the reference in this as a variable and then inherit it through a closure. Such as:
Or, in newer browsers, use the bind() method to pass a reference:
7. Uncaught RangeError: Maximum Call Stack
This is a bug that happens in Chrome in a number of ways, one of which is when you call a recursive function that doesn’t terminate.
This can also happen if the value is passed to a function that is out of scope. Many functions only accept numeric input values within a specific range. For example, number.tofixed (digits) and number.tofixed (digits) accept values ranging from 0 to 20, while number.toprecision (digits) accepts values ranging from 1 to 21.
TypeError: Cannot Read Property ‘length’ 8. TypeError: Cannot Read Property ‘length’
This is an error in Chrome because a variable with an undefined length attribute was read.
You can usually find the defined length in an array, but this error can occur if the array is not initialized or if the variable name is hidden in another context. Let’s use the following example to explain this mistake.
When you declare a function with arguments, those arguments become local arguments. This means that even if you have the named variable testArray, arguments in a function with the same name are still treated as local arguments.
There are two ways to solve this problem:
1). Delete parameter from function declaration statement:
2). Call the array function passed to our declaration:
9. Uncaught TypeError: Cannot Set Property
Undefined is always returned when you try to access an undefined variable. We also cannot get or set any properties of undefined. In this case, the application will throw “Uncaught TypeError cannot set property of undefined”.
For example, in Chrome, this error occurs if the test object does not exist:
So you need to define variables before you access them.
10. ReferenceError: Event Is Not Defined
This error is raised when you try to access an undefined variable or a variable outside the current scope.
If you encounter this error when using the event handling system, be sure to use the event object passed in as a parameter. Browsers like Internet Explorer provide global variable events, which Chrome automatically appends to handlers, and Firefox does not.
JavaScript development tools are recommended
SpreadJS is an HTML5-based JavaScript spreadsheet and grid control that provides a complete formula engine, sorting, filtering, input controls, data visualization, Excel import/export, and more. For.net, Java and mobile terminal and other platforms online editing Excel function of the form program development.
conclusion
It turns out that many of these null or undefined errors are common. A good static type checking system like Typescript can help developers avoid these errors when set to strict compilation options.
Finally, I hope this article can help developers better avoid or deal with the above 10 mistakes.
English: Jason Skowronski
The Grape City control
www.cnblogs.com/powertoolsteam/p/top-10-javascript-errors.html