11 Common Errors in JavaScript programming

Source: Internet
Author: User

Javascript is easier to learn. However, you need to pay attention to this language. This article will point out 10 possible errors in JavaScript programming.

Error 1-use global variables

If you have just started JavaScript programming, you may feel that global variables are useful. In fact, at the beginning of JavaScript programming, you may not know how troublesome it will be to use global variables. On the same page, global variables can be accessed in any embedded Javascript code segment or in different JS files loaded on the page. It sounds powerful, right? This allows global variables to be modified and assigned values anytime, anywhere.
In fact, this is really bad!
This will cause the variable to be modified and rewritten unexpectedly. Suppose there is an online store that needs to be calculated using JavaScript and show the total price of all the items in the shopping cart (of course, the server side will re-calculate the price to enhance the user experience ). You may write the following code:

var total = 0, // total pricetax = 0.05; // 5%

Now, you also need to use JavaScript code to display some information on the website, or create a product repository. The Code is as follows:

var total = 15; // number of tweets pulled from twitter

Or the following code is used:

var tax = function () { /* ... */ }; // Trigger Animation eXperience function

Now there is a problem: two important variables are overwritten, but they may not be realized yet. In this way, an error occurs during code running, and it takes a lot of time to track and fix the error.
How can this problem be solved? In short-"encapsulation": of course there are many methods to encapsulate it. The first method is to put the code into an anonymous self-tuning function. The Code is as follows:

(function () { var total = 0, tax = 0.05;  // other code }());

In this way, variables defined inside the function cannot be accessed outside the function. This forms a personal code space, but thus some methods or attributes cannot be disclosed. For example, to create a shopping cart and define a variable of the total price as a public attribute, modular programming can be used in this case.

var cartTotaler = (function () { var total = 0; tax = 0.05;  // other code  return { addItem : function (item) { }, removeItem : function (item) { }, calculateTitle : function () { } }; }());

It is worth noting that if the keyword VaR is not used to declare the creation of a global variable, the JavaScript engine defines the variable as a global variable by default.

(function () { tax = 0.05; }());  var totalPrice = 100 + (100 * tax); // 105

The variable tax can also be accessed outside the function, because the VaR keyword is not used when tax is defined.

Error 2-no credit points

Each JavaScript statement must end with a semicolon. If you forget the extra points during programming, the Javascript parser will automatically add them. So when programming, do we have to waste time adding points?
However, in some statements, semicolons are essential. For example, the semicolon in the for loop statement is essential; otherwise, a syntax error is reported. What about the semicolon at the end of the statement?
This issue has been discussed in the Javascript community. The following is my opinion in this article: As long as your code has been modified by the Javascript Parser (even a small modification, such as adding a semicolon), some unexpected results may appear. Take a look at the following JavaScript code:

function returnPerson (name) { return { name : name }; }

This method seems to return an object, but in fact, the Javascript parser will add a semicolon after the return, which causes the function to return undefined. Objects after return are ignored. The solution is simple. The Code is as follows:

return { name : name };

In JavaScript programming, you should strictly require yourself to add a semicolon, which is not difficult. Of course, as a web developer, you may also use other languages (such as PHP) that strictly require a semicolon to end. You can bring the habits of these programming languages to JavaScript programming.
Note: you cannot ignore the addition of semicolons unless you are absolutely certain to be ignored.

Error 3-use =

If you ask a javascript programmer, what are common mistakes in JavaScript programming. He/she may say that = is used instead of =. What does this mean?
Try the following code:

if (1 == 1) { console.log("it's true!"); }

The Code outputs "it's true!" as you wish !" Then try the following code:

if (1 == '1') { console.log("it's true!"); }

The Code also outputs "it's true!" in the console !", However, this is not the expected output. Here the = Operator converts the type of the Operation number, so that the two operations are equal. Here, the = operator in the IF statement changes "1" of the string type on the right to 1 of the number type.
To get the output you want, replace = with the = Operator. ===The type of the Operation number is not forcibly converted, so that it can be as expected. Similarly, use! = Operator to replace! =. The following is a comparison using =. The result is surprising.

'' == '0' // false '0' == '' // true false == '0' // true ' \t\r\n ' == 0 // true

Error 4-use a data-type packaging object

Javascript provides packaging objects of various data types.

new Number(10); new String("hello"); new Boolean(true); new Object(); new Array("one", "two", "three");

First, they are not easy to use. The above code can be implemented with less code, as shown below:

10; "hello"; true; {}; ["one", "two", "three"];

However, these two methods are different. Douglas crockford's point of view is as follows:
For example, you can use new Boolean (false) to create an object with the valueof method. If you call this method, the value of the constructor is returned.
This means that if typeof new number (10) or typeof new string ('hello') is run, 'object' is returned instead of 'number' or 'string '. in addition, packaging data types can lead to unexpected results.
So why does JavaScript provide packaging objects of the Data Type? This is because the Javascript parser calls it internally. Simple data types have no method (because they are not objects), so when calling simple data methods (such as 'hello '. replace ('Ello ',' I '), JavaScript will call the string packaging object to create a temporary String object, and then call the method of this object, the temporary object will be deleted after the call is completed.
Therefore, do not use data-type packaging objects to create simple data types.
Note: I don't need to explain this, but this article is still intended to clearly tell beginners: It doesn't mean not to use them or new (although some of them are recommended). It should be noted here that, we recommend that you specify these data types, such as number, String, Boolean, array, and empty objects.

Error 5-attributes are not checked when you use for-in.

We are all familiar with traversing arrays, but you may want to traverse the attributes of objects. (Subject: array is actually an object named number ). You can use the for-in loop statement. The Code is as follows:

var prop, obj = { name: "Joe", job: "Coder", age: 25 };  for (var prop in obj) { console.log(prop + ": " + obj[prop]); }

Run the above Code and output the following:

name: Joe job: Coder age: 25

However, when the browser for-in traverses object attributes and methods, it will include all attributes and methods on the object prototype chain. However, most attributes do not need to be enumerated. You can use the hasownproperties method to check whether a property belongs to an object. The Code is as follows:

Function Dog (name) { this.name = name; } Dog.prototype.legs = 4; Dog.prototype.speak = function () { return "woof!"; };  var d = new Dog("Bowser");  for (var prop in d) { console.log( prop + ": " + d[prop] ); }  console.log("=====");  for (var prop in d) { if (d.hasOwnProperty(prop)) { console.log( prop + ": " + d[prop] ); } }  // Output  // name: Bowser // legs: 4 // speak: function () { return "woof!"; // } // ===== // name: Bowser

Sometimes, you only want to enumerate the attributes of objects, excluding methods. You can use the typeof method. The Code is as follows:

for (var prop in d) { if (typeof d[prop] !== 'function') { console.log( prop + ": " + d[prop] ); } }

In any case, when using a for-in loop, make sure that the attribute is checked to avoid unexpected results.

Error 6-use with or eval

Fortunately, most JavaScript tutorials do not teach you how to use with or eval. But some old tutorials or well-known materials (sometimes it is difficult to find good information on the Internet) may find that with or Eval is used.
The following are two main reasons for not using:
1. It will reduce Code Performance
2. Not easy to read code

The first point is inherent. Second, let's look at the following code. Here we use with to access the name and age attributes of the person object.

var person = { name: "Joe", age : 10 };  with (person) { console.log(name); // Joe console.log(age); // 10 }

However, if there is a variable with the same name as one of the objects, what will happen with "? In fact, in this case, the access variable will reference the variable instead of the object attribute. In the with statement, if the accessed attribute does not exist or the object does not exist, you cannot add an attribute to the object, at the same time, a variable will be created in the scope after the with scope on the scope chain.

var person = { name: "Joe", age : 10 }, name = "Billy";  with (person) { console.log(name); // Billy job = "Designer"; }  console.log(person.job); // undefined; console.log(job); // Designer

What about Eval? It can accept a string parameter and parse and modify the string.

It sounds nothing bad, or even great, right? But the problem is that this is amazing! Instead of parsing and executing a series of strings, why not write them directly in the program? The reasons for not doing this are as follows:

  1. It can be directly written in the code.
  2. Eval resolution is slow, and the performance is similar to.

Eval is used in non-runtime environments. You can obtain code from the server or client. Do you really want your website users to control your code? This does not mean that your website is open to countless hackers. Using Eval is like leaving home and telling everyone that the key is under the door mat. If you love yourself or your users, do not use eval.

Error 7-no base number is used when parseint is used

Javascript provides a very useful method of parseint, which can convert a string to a value.

parseInt("200"); // 200 parseInt("043"); // 35

Is the result surprising? The second sentence is not 43. Why? In fact, the parseint method not only converts strings into decimal numbers. When the first parameter of parseint starts with 0, it converts the string into an octal number. This is the unexpected result of not using the base number. The second parameter-base, which specifies the number of hexadecimal strings used by the parseint method. (Of course, its return value is always in decimal format)

parseInt("020", 10); // 20 parseInt("100", 2); // 4

Error 8 If and while statements do not use {}

The most obvious characteristic of JavaScript is that the syntax requirements are not so strict. However, it is such a characteristic that sometimes it will cause troubles. If and while statements {} will cause some trouble. {} Is used based on the number of code statements executed when the if condition is set.

if (true) console.log("inside the if statement");

It seems that there is no problem here, because there is only one execution statement

var arr = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"], i = arr.length - i;  while (i) console.log( arr[i--] );

But this is not easy to read: first, the {} code structure does not seem so clear.

if (true) console.log("inside the if-statement."); console.log("outside the if-statement.");

Look at the code above. The console statement in the second line does not belong to the IF statement, but it looks like the if statement. Using {} makes the structure clearer. In addition, if you want to add a sentence to the IF Execution Code, you also need to use {}. It is not difficult to use.

Error 9-insert a single Dom Element

This is not a javascript issue. 99% of JavaScript programming involves Dom operations. Many errors may be made in Dom operations, but this is the most obvious one.
Dom operations may cause the browser to re-paint the page. Therefore, if a series of elements are inserted to the page one by one, this will greatly increase the burden on the browser to render the page.

var list = document.getElementById("list"), items = ["one", "two", "three", "four"], el;  for (var i = 0; items[i]; i++) { el = document.createElement("li"); el.appendChild( document.createTextNode(items[i]) ); list.appendChild(el); // slow, bad idea }

Document fragments is a DOM element container that can be used to add these elements to the page at the same time. Document fragment itself is not a DOM node. It is not displayed in the DOM tree of the page and is invisible before it is inserted into the Dom. The following is its usage:

var list = document.getElementById("list"), frag = document.createDocumentFragment(), items = ["one", "two", "three", "four"], el;  for (var i = 0; items[i]; i++) { el = document.createElement("li"); el.appendChild( document.createTextNode(items[i]) ); frag.appendChild(el); // better! }  list.appendChild(frag);

Very fast and concise!

Error 10-do not understand Javascript

Many people do not take the time to seriously learn JavaScript.
Javascript is not the same as jquery. Are you scared? If you make the above listed errors, you need to learn JavaScript carefully. Javascript is a language that can basically be used without learning. As a result, many people do not take the time to study it seriously. Do not do this. There are too many Tutorials that point out the disadvantages of doing so. You have no excuse not to seriously study JavaScript. If you only know jquery (or mootools, or something else), the starting point for learning Javascript is already wrong.

Error 11-strictly follow the above rules

"Rules are made to be broken ."(Rules are used to be broken .)

Although the above rules are listed in this article, the rules are used to be broken just like anything else. If you are learning JavaScript at the beginning, you will strictly abide by the above rules. However, after you understand why the above rules must be followed, you will be able to use the rules flexibly. For example, Eval is the only method that can parse the JSON string returned by the server. Of course, a lot of security checks will be performed when you use it (You may use a javascript library ). What you want to specify here is that you should not be afraid of making mistakes and use it boldly wherever necessary. Of course, never make mistakes.

Conclusion:

If you are a beginner in Javascript, I hope the above content will be helpful for your JavaScript programming. If you are a senior JavaScript engineer, leave a message on the message board to inform you of any omissions.

This article is translated from the 11 JavaScript mistakes you're making.

Related Article

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.