10 Common JavaScript bugs

Source: Internet
Author: User
Tags sublime text

Translator by: in the development of security, I basically do not use = =.

    • Original: Ten COMMON JAVASCRIPT BUGS and how to AVOID them
    • Translator: Fundebug

In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.

Even the most awesome JavaScript developers make mistakes. Sometimes the result of the execution of the program is not the same as expected, and sometimes it cannot run at all. I've summed up 10 common mistakes here, and I'm sure that both junior and senior developers are likely to meet.

Equal confusion

is x equal to Y? Is x true? In JavaScript, it is important to make equal judgments correctly, but many people seem to be confused. Briefly summarize the following three situations: conditional judgment (if, &&, etc.), equality operator (= =), and strict equality operator (= = =).

Even if you accidentally use an assignment (=) as an equal operator, don't make a mistake!

Avoid using assignments (=)

Assignment (=) assigns the right expression to the left variable, for example:

3;

The statement declares a new variable with a a value of 3.

An expression can be anything in a program, imagine analogy to a noun in a language, an operator (+,-, *,/) analogy to a verb. A common mistake for beginners is to misuse the assignment (=) as an equality judge.

if (a=4) {...}

The code does not perform as expected.

Use equality operators with caution

The equality operator (= =) and his twin inequality operator (! =) are very useful, but they are also dangerous to use sparingly. Next, let's explain why:

' 0 '

Under the equal sign, 0 and 0 is equal! Because the interpreter finds inconsistencies between the left and right types, an implicit type conversion is first done. This can cause a variety of problems, and then it's hard to find the cause of the problem.

If you really want to tell if a string contains numbers and if a number is really the same, it is recommended that you do this:

parseint (parseint (' 0 ')

Therefore, it is recommended to use strictly equal/unequal operators.

' 0 '

will return false .

Missing curly Braces

When the program becomes complex, especially if you use JavaScript objects to store data, the curly braces will be more and more. Here is a piece of code, but a brace is missing:

 {
' status ': ' OK ',
' results ': [{
12,
Span class= "line" _ "Author": "Chris Minnick and Eva Holland",
Span class= "line" and "url": "",
of Coding JavaScript for Dummies '
},
' awards ': [{
}]

Can you see what's missing? A good editor can be very useful when you are unsure. Sublime TextThere's a nice feature, and when you put the cursor in a brace, the curly braces that match it are highlighted.


Mismatched quotes

When defining a string, you are free to use either single quotation marks or double quotes. However, if a single quoted string starts, the double quotation mark ends. And you need to pay attention to the single quotation mark or double quotation mark in the string itself.

error!
error!

In general, the individual is considered to be a very flexible and useful function, but must be careful!

Lack of necessary parentheses

This error is often at the time of a conditional statement error, especially when there are multiple conditions.

1000) {
...
}

If you look at it, you'll notice that the brackets are missing, and the correct one should be:

1000)) {
...
}

Missing semicolon

The statements in JavaScript should end with semicolons. But if these statements are on one line, it doesn't matter if you don't write semicolons. However, it is not recommended because there are potential problems. If you use the Automatic Code beautification tool It may be wrong to merge the code that is not in line with the error.

The best strategy is to add semicolons.

Capitalization error

JavaScript is case-sensitive, you need to be careful about the names of variables and functions, and you can't mistake the case. For example, the function of the Document object getElementById is often written incorrectly getElementByID .

Refer to before loading

JavaScript code is usually executed sequentially, and if you reference an element that is created later, it will be an error.


<script>
document.getElementById ("Mydiv"). InnerHTML = "This div is my div";
</script>
<body>
<div id = "Mydiv" >this div is your div.</div>
</body>
</html>

When the script executes, the browser does not yet know myDiv what it is.
There are many ways to avoid this problem:

    • puts the code at the end, which is </body> after
    • places the code in the function, and binds onload to the body .
  <HEAD> 
function namemydiv ( document.getElementById ("Mydiv"). InnerHTML = "This div is my div";
/SCRIPT>
< Span class= "RegExp" ></HEAD>
<body onload = "namemydiv ();"
/DIV>
</body>,
</HTML>
Abusing reserved words to do variable names

One problem that is hard to track is the use of reserved words for variable names. There are more than 60 reserved words in JavaScript. Of course, you can't all memorize them to avoid using them. The best way to name variables is to use more descriptive characters.

An example name is a reserved word. If you like to use name , then the best refinement, for example firstName , lastName , dogName and nameOfTheWind .

Scope issues

There are function scopes and global scopes in JavaScript. If you do not use var keywords to declare, then it is global. To ensure secure isolation of different scopes, it is recommended var . Translator Supplement: Recommended use let , more secure, can refer to this article: ES6 "let" can replace "var"?

Function call missing parameter

In JavaScript, there are several parameters that are missing from the function call and sometimes do not go wrong, but may not achieve the expected execution results. So, make sure you pass in enough function arguments.

Starting from 0

Never forget that the array is starting from 0.


Array ();
myarray[Common mistakes ";
Output 11!

Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2017/12/18/10- common-javascript-bugs-and-how-to-avoid-them/

10 Common JavaScript bugs

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.