Summary of JavaScript syntax error-prone aspects

Source: Internet
Author: User
Tags readable

JavaScript is a dynamic scripting language with a high degree of grammatical freedom and incomplete design maturity. Because of its highly flexible syntax and a variety of other reasons, the code written with it is extremely readable (at least I feel). In contrast, the Python language syntax is most recommendable in many of the languages I have known.

In this article I try to record and gradually add to the use of JS error-prone grammatical expressions and some difficulties, and try to add to the top display after each.

var use

It is not safe to omit Var when defining a variable, but it is legal. The scope of the defined variable depends on the defined location. whenever the variable is defined in any location, the interpreter assigns the variable to the global scope .

Some of the JavaScript programming styles recommended by Crockford

Note: This section is from Nanyi's blog "http://www.ruanyifeng.com/blog/2012/04/javascript_programming_style.html".

1. Position of curly braces
===================

Because JavaScript automatically adds a semicolon at the end of a sentence, it causes some imperceptible errors.
Return
{
Key:value;
};
The original intent of the above code is to return an object, but it actually returns undefined, because JavaScript automatically adds a semicolon after the return statement. To avoid this type of error, you need to write the following:
return {
Key:value;
};


  Rule 1: The curly brace that represents the beginning of the block, not another line.

2. Parentheses
===============

Parentheses (parentheses) have two functions in JavaScript, one for calling a function and another for a combination of different values (grouping). We can use spaces to distinguish between these two different parentheses.

Rule 2: When calling a function, there is no space between the function name and the opening parenthesis.
Rule 3: There is no space between the function name and the parameter sequence.
Rule 4: There is a space between all other syntax elements and the opening parenthesis.

According to the above rules, the following wording is not standard:
Foo (BAR)
return (A+B);
if (a = = 0) {...}
function Foo (b) {...}
function (x) {...}

3. Semicolon
====================

A semicolon indicates the end of the statement. In most cases, if you omit the semicolon at the end of the sentence, JavaScript is automatically added.
var a = 1
Equivalent to
var a = 1;
Therefore, it is advocated to omit the semicolon at the end of the sentence. But the trouble is, if the first character (token) of the next line is one of these five characters, JavaScript will not add a semicolon to the end of the previous line: "(", "[", "/", "+" and "-".)
x = y
(function () {
...
})();
The above code is equivalent to
x = y (function () {...}) ();
So
  Rule 5: Do not omit the semicolon at the end of the sentence.

4.with statements
=====================

With can reduce the writing of code, but can cause confusion.
With (o) {
foo = bar;
}
The above code, can have four kinds of running results:
O.foo = bar;
O.foo = O.bar;
foo = bar;
foo = O.bar;
All four of these results can occur, depending on whether or not different variables are defined. So

  Rule 6: Do not use the WITH statement.

5. Equal and Strictly equal
===================

JavaScript has two operators that represent equality: equality (= =) and strict equality (= = =).
Because the equality operator automatically converts variable types, it causes many unexpected situations:
0 = = "'//True
1 = = TRUE//True
2 = = TRUE//False
0 = = ' 0 '//True
False = = ' false '//False
false = = ' 0 '//True
"\t\r\n" = = 0//True
So
  Rule 7: Do not use the equality (= =) operator, only the strict equality (= = =) operators.

6. Merging of statements
======================

Some programmers pursue brevity and prefer to combine statements of different purposes. For example, the original statement is
A = b;
if (a) {...}
He likes to write the following:
if (a = b) {...}
Although the statement is one line less, but the readability is greatly discounted, and can cause misreading, let others mistakenly think this line of code means:
if (a = = B) {...}
Another scenario is that some programmers prefer to assign multiple variables in the same row:
var a = b = 0;
He thought that this line of code was equivalent to
var a = 0, b = 0;
Actually not, its real effect is the following:
b = 0;

var a = b;
So

  Rule 8: Do not combine statements of different purposes into one line.

7. Variable declaration
======================

JavaScript automatically declares the variable "lifted" (hoist) to the head of the code block (block).
if (!o) {
var o = {};
}
Equivalent to
var o;
if (!o) {
o = {};
}
To avoid a possible problem, put the variable declaration in the head of the code block.
for (var i ...) {...}
Best written:
var i;

for (I ...) {...,}
So
  Rule 9: All variable declarations are placed on the head of the function.
Rule 10: All functions are defined before they are used.

8. Global variables
===================

The biggest grammatical disadvantage of JavaScript is that global variables are readable and writable for any block of code. This is very detrimental to the modular and repetitive use of code.

  Rule 11: Avoid using global variables; If you have to, use uppercase letters to denote variable names, such as Upper_case.

9.new command
===================

JavaScript uses the new command to generate a new object from the constructor.
var o = new MyObject ();
The problem with this approach is that once you forget to add New,myobject () The inside of the This keyword will point to the global object, causing all the variables bound on this to become all variables.

  Rule 12: Do not use the new command instead of the object.create () command.

If you have to use new, it's a good idea to visually distinguish constructors from other functions in order to prevent errors.
  Rule 13: The function name of the constructor, with the first letter capitalized (INITIALCAP), the other function name, all the first letter lowercase.

10. Self-increment and decrement operators
==========================

The increment (+ +) and decrement (-) operators, placed before or after a variable, return a different value and are prone to errors.
In fact, all the + + operators can be replaced with "+ = 1".
++x
Equivalent to
x + = 1;
The code becomes clearer. There is a ridiculous example where the following fragment appears in the source code of a JavaScript library:
++x;
++x;
The programmer forgot that there was a simpler and more reasonable notation:
x + = 2;
So

  Rule 14: Do not use the self-increment (+ +) and decrement (-) operators, substituting + = and-=.

11. Block
=====================

If there is only one line in the loop and judging code body, JavaScript allows the block to omit the curly braces.
The following code
if (a) B (); C ();
The original intention may be
if (a) {B (); C ();}
However, the actual effect is
if (a) {B ();} c ();
So

  Rule 15: Always use curly braces to represent chunks.

This article is from the "Green Peak" blog, please make sure to keep this source http://zhuxianzhong.blog.51cto.com/157061/1615048

Summary of JavaScript syntax error-prone aspects

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.