10 most common Javascript errors (highest frequency) and javascript frequency

Source: Internet
Author: User
Tags chrome developer

10 most common Javascript errors (highest frequency) and javascript frequency

In order to give back to our developer community, we checked the databases of thousands of projects and found 10 errors with the highest intermediate frequency in JavaScript. We will tell you what causes these errors and how to prevent them. If you can avoid falling into these "traps", you will become a better developer.

Data is king. We have collected and analyzed the top 10 JavaScript errors. Rollbar collects all errors of each project and summarizes the number of errors. We grouped errors by following the "fingerprint" (an algorithm used by rollbar, see: https://rollbar.com/docs/grouping-algorithm. Basically, if the second error is a duplicate of the first error, we will divide the two errors into the same group. This will give the user a good summary, rather than a bunch of dump that can be seen in the log file.

We focus on errors that are most likely to affect you and your users. To this end, we arrange errors by studying project sets of different companies. If we only view the total number of times each error occurs, errors generated by a large number of projects of the customer may overwhelm other errors, resulting in the actual collection of error datasets unrelated to most readers.

The following are Top 10 JavaScript errors:

For ease of reading, we have reduced every error description. Next, let's go deep into every error to determine what will cause it and how to avoid creating it.

1. Uncaught TypeError: Cannot read property

If you are a JavaScript developer, you may see this error more times than you can admit (LOL ...). This error occurs in Chrome when you read an undefined object property or call its method. You can easily perform a test on the Chrome developer console ).

There are many reasons for this, but the common one is that initialization of the status is improper when rendering the UI component.

Let's look at an example in a real application: We chose React, but this also applies to Angular, Vue, or any other framework.

class Quiz extends Component { componentWillMount() {  axios.get('/thedata').then(res => {   this.setState({items: res.data});  }); } render() {  return (   <ul>    {this.state.items.map(item =>     <li key={item.id}>{item.name}</li>    )}   </ul>  ); }}

There are two important things to achieve:

The component status (such as this. state) starts from undefined.

When data is obtained asynchronously, whether it is obtained in the constructor componentWillMount or componentDidMount, the component is presented at least once before the data is loaded. When Quiz is rendered for the first time, this. state. items is undefined. This means that ItemList defines items as undefined, and an error occurs in the console-"Uncaught TypeError: Cannot read property 'map' of undefined ".

This is easy to solve. The simplest method is to use a reasonable default value in the constructor to initialize the state.

class Quiz extends Component { // Added this: constructor(props) {  super(props);  // Assign state itself, and a default value for items  this.state = {   items: []  }; } componentWillMount() {  axios.get('/thedata').then(res => {   this.setState({items: res.data});  }); } render() {  return (   <ul>    {this.state.items.map(item =>     <li key={item.id}>{item.name}</li>    )}   </ul>  ); }}

The specific code in your application may be different, but we hope we have given you enough clues to solve or avoid this problem in your application. If you do not have one, continue reading as we will cover more examples of related errors below.

2. TypeError: 'undefined' is not an object

This is an error when reading properties in Safari or calling methods on undefined objects. You can easily test it in the Safari Developer Console. This is basically the same as the Chrome error mentioned in 1, but Safari uses different error message prompts.

3. TypeError: null is not an object

This is an error when reading attributes in Safari or calling methods on empty objects. You can easily test it in the Safari Developer Console.

Interestingly, in JavaScript, null and undefined are different, which is why we see two different error messages. Undefined is usually an unallocated variable, and null indicates that the value is null. To verify that they are not equal, try to use the strict equality operator ===:

In a real-world example, this error may occur when elements are used in JavaScript before being loaded. Because DOM APIs return null values for Blank object references.

Any JavaScript code that executes and processes DOM elements should be executed after DOM elements are created. The JS Code is interpreted from top to bottom according to the instructions in HTML. Therefore, if there is a tag before the DOM element, the JS Code in the script tag will be executed when the browser parses the HTML page. This error occurs if you have not created a DOM element before loading the script.

In this example, we can add an event listener to solve this problem. This listener will notify us when the page is ready. Once the addEventListener is triggered, the init () method can use the DOM element.

<script> function init() {  var myButton = document.getElementById("myButton");  var myTextfield = document.getElementById("myTextfield");  myButton.onclick = function() {   var userName = myTextfield.value;  } } document.addEventListener('readystatechange', function() {  if (document.readyState === "complete") {   init();  } });</script><form> <input type="text" id="myTextfield" placeholder="Type your name" /> <input type="button" id="myButton" value="Go" /></form>

4. (unknown): Script error

This type of script error is generated when uncaptured JavaScript errors (errors caused by processing programs through window. onerror, rather than being captured in try-catch) are restricted by the browser's Cross-Domain Policy. For example, if you host your JavaScript code on CDN, any uncaptured errors will be reported as "script errors" rather than containing useful stack information. This is a browser security measure designed to prevent cross-Origin data transmission. Otherwise, communication is not allowed.

To obtain a real error message, perform the following operations:

1. Send the 'access-Control-Allow-origin' Header

Setting the Access-Control-Allow-Origin header to * indicates that resources can be correctly accessed from any domain. If necessary, you can replace the domain with your domain: for example, Access-Control-Allow-Origin: www.example.com. However, processing multiple domains becomes tricky. If you use CDN, more cache problems may cause you to feel that this effort is not worthwhile. See more here.

Here are some examples of how to set this header file in various environments:

Apache

In the folder where the JavaScript file is located, use the following content to create a. htaccess file:

Header add Access-Control-Allow-Origin "*"

Nginx

Add the add_header command to the location block that provides the JavaScript file:

Location ~ ^/Assets/{add_header Access-Control-Allow-Origin *;}

location ~ ^/assets/ {  add_header Access-Control-Allow-Origin *;}

HAProxy

Add the following content to the backend where you provide resource services for JavaScript files:

Rspadd Access-Control-Allow-Origin :\*

Rspadd Access-Control-Allow-Origin :\*

2. Set crossorigin = "anonymous" in <script>"

In your HTML code, set crossorigin = "anonymous" on the script tag for each script with Access-Control-Allow-Origin header set ". Before adding the crossorigin attribute to the script tag, ensure that the above header is correctly sent. In Firefox, if the crossorigin attribute exists but the Access-Control-Allow-Origin header does not exist, the script will not be executed.

5. TypeError: Object doesn' t support property

This is an error that occurs in IE when you call an undefined method. You can test on the IE developer console.

This is equivalent to the "TypeError:" undefined "is not a function" error in Chrome. Yes. For the same logic error, different browsers may have different error messages.

For Web applications that use JavaScript namespaces, This is a common problem with IE l browsers. In this case, 99.9% is because IE cannot bind the methods in the current namespace to the this keyword. For example, if your JS contains a namespace Rollbar and the isAwesome method. Generally, if you are in a Rollbar namespace, you can use the following syntax to call the isAwesome method:

this.isAwesome();

Chrome, Firefox, and Opera will readily accept this syntax. On the other hand, IE does not. Therefore, when using the JS namespace, the safest choice is always to use the actual namespace as the prefix.

Rollbar.isAwesome();

6. TypeError: 'undefined' is not a function

This is an error in Chrome when you call an undefined function. You can perform tests on the Chrome developer console and Mozilla Firefox developer console.

As JavaScript coding technology and design patterns have become more and more complex over the past few years, the auto-reference range in callback and closure has also increased, which is a fairly common source of confusion.

Consider this code snippet:

function testFunction() { this.clearLocalStorage(); this.timer = setTimeout(function() {  this.clearBoard();  // what is "this"? }, 0);};

Executing the above Code will cause the following error: "Uncaught TypeError: undefined is not a function ". The reason you get the above error is that when you callsetTimeout()Is actually calledwindow.setTimeout(). Therefore, in the context of the window object,setTimeout()The anonymous function of. This function does not haveclearBoard()Method.

A traditional solution that is compatible with the old browser is to simply save your this in a variable, which can then be inherited by the closure. For example:

function testFunction () { this.clearLocalStorage(); var self = this;  // save reference to 'this', while it's still this! this.timer = setTimeout(function(){  self.clearBoard();  }, 0);};

Alternatively, you can use the bind () method to pass the appropriate reference in a newer Browser:

function testFunction () { this.clearLocalStorage(); this.timer = setTimeout(this.reset.bind(this), 0); // bind to 'this'};function testFunction(){  this.clearBoard();  //back in the context of the right 'this'!};

7. Uncaught RangeError: Maximum call stack

This is a Chrome error in some cases. One is when you call a non-terminating recursive function. You can perform a test on the Chrome developer console.

This can also happen if you pass the value to a function that is out of the range. Many functions only accept numbers in a specific range of their input values. For example, Number. toExponential (digits) and Number. toFixed (digits) accept numbers from 0 to 20, and Number. toPrecision (digits) accept numbers from 1 to 21.

var a = new Array(4294967295); //OKvar b = new Array(-1); //range errorvar num = 2.555555;document.writeln(num.toExponential(4)); //OKdocument.writeln(num.toExponential(-2)); //range error!num = 2.9999;document.writeln(num.toFixed(2));  //OKdocument.writeln(num.toFixed(25)); //range error!num = 2.3456;document.writeln(num.toPrecision(1));  //OKdocument.writeln(num.toPrecision(22)); //range error!

8. TypeError: Cannot read property 'length'

This is an error in Chrome because the Length attribute of the undefined variable is read. You can perform a test on the Chrome developer console.

You usually find the defined length in the array, but this error may occur if the array is not initialized or the variable name is hidden in another context. Let's use the following example to understand this error.

var testArray = ["Test"];function testFunction(testArray) {  for (var i = 0; i < testArray.length; i++) {   console.log(testArray[i]);  }}testFunction();

When you declare a function with parameters, these parameters become local parameters in the function scope. This means that even if your function has a variable named testArray, parameters with the same name in a function are considered as local parameters.

You can solve your problem in two ways:

1. Delete the parameters in the function declaration statement (in fact, you want to access the variables declared outside the function, so you do not need the function parameters ):

var testArray = ["Test"];/* Precondition: defined testArray outside of a function */function testFunction(/* No params */) {  for (var i = 0; i < testArray.length; i++) {   console.log(testArray[i]);  }}testFunction();

2. Call this function using declared Arrays:

var testArray = ["Test"];function testFunction(testArray) {  for (var i = 0; i < testArray.length; i++) {   console.log(testArray[i]);  }}testFunction(testArray);

9. Uncaught TypeError: Cannot set property

When we try to access an undefined variable, it always returns undefined, and we cannot get or set any undefined attributes. In this case, the application will throw "Uncaught TypeError: Cannot set property ".

For example, in Chrome:

If the test object does not exist, the error will throw "Uncaught TypeErrorUncaught TypeError: Cannot set property ".

10. ReferenceError: event is not defined

This error is thrown when you try to access undefined variables or variables out of the current range. You can easily test it in Chrome.

If you encounter this error when using the event processing system, make sure that the passed event object is used as the parameter. An old browser like IE provides a global variable event, but not all browsers support it. Libraries such as jQuery try to normalize such behavior. However, it is best to use the function that passes in the event processing function.

function myFunction(event) {  event = event.which || event.keyCode;  if(event.keyCode===13){    alert(event.keyCode);  }}

Summary

The above is the 10 most common Javascript errors introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.