The JavaScript dross and the ribs I know

Source: Internet
Author: User
Tags bitwise operators hasownproperty

drossGlobal Variables

It is well known that global variables may be convenient in very small programs, but as programs become larger, global variables will be difficult to handle, and global variables will reduce program reliability.

There are 3 ways to define global variables in JS

Out of any function to arrange a var statement//var Foo=value;

Add a property directly to the global object on the//window.foo=value;

Direct use of undeclared changes (in fact, this is called Hidden global variables) //foo=value;   

Scope

As we all know, there is no block-level scope in JavaScript, and in JavaScript there is the ability to promote variable declarations, so it is best to declare all variables at the beginning of each function.

automatically inserting semicolons

JavaScript attempts to fix a defective program by automatically inserting a semicolon.

        return         {            Status:true        };

The code above will naturally be expected to return an object that contains the status member element. But since JavaScript is automatically inserted, it becomes a return undefined.

So put {on the tail of the previous line instead of the next line of the head to avoid the above problem

Reserved Words

When reserved words are used as key values for object literals, they must be enclosed in quotation marks. They cannot be used in point notation, so it is sometimes necessary to use parentheses notation.

It's best not to use reserved words for identifiers. javascript reserved words are listed as slices

Unicode

The encoding of JavaScript is particularly clearly illustrated in a blog post in Ruan Yi, in Unicode and JavaScript.

A short description is that JavaScript characters are 16-bit , so in terms of coding many characters are very difficult to express.

typeof

typeof Null returns an object

typeof/a/some will return as object while others return function

parseint

Converts a string to an integer, but stops parsing when it encounters a non-digit.

If the first character of the string is 0, the string will be evaluated based on octal instead of decimal. (But the key is that browsers that are below IE8 are still evaluated as decimal values.)

It is recommended that you provide cardinality parameters when using parseint, even if you are converting to decimal.

+

+ is used primarily for addition operations or string connections. But as long as one of the characters is a string, the string is returned

So when you're going to do the addition operation with +, make sure that two operands are integers.

floating point number

In JavaScript, 0.1+0.2 is not equal to 0.3.

Integer operations in floating-point numbers are accurate, so the errors shown by decimals can be avoided by specifying the precision.

NAN

typeof cannot discern numbers and Nan, and it turns out that Nan is not equal to its own

        function Isnumber (value) {            returntypeof value = = = ' Number ' && isfinite ( value);        }
Pseudo-Array

There is no real array in JavaScript ! In other programming languages, arrays are indexed by numbers, but in fact there is no array in JavaScript, and arrays and objects are not really very different, JavaScript provides an object of class array attributes, which converts array subscripts to strings, and uses them as attributes. Properties are checked and updated in exactly the same way as objects except for an attribute that can be used as an integer attribute name.  

        // determines whether an array        function IsArray (value) {            return value &&                    typeof value = = = ' object ' &&                    typeof Value.length = = = ' Number ' &&                    typeof Value.splice = = = ' function ' &&                    ! ( Value.propertyisenumerable (' length '));        };

False Value

You have a lot of fake values in JavaScript, as shown in. undefined and Nan are not constants, they are global variables, and you can change their values .

hasOwnProperty

As we all know, the hasOwnProperty method is used by a filter to avoid the for in statement because it is just a method, so in any object it may be replaced by a different function or even a non-function value.

        var another = {};         var name;         NULL // This modifies the hasOwnProperty method to a non-function value         for inch another) {            if  (Another.hasownproperty (name)) {                //  The result of using hasOwnProperty here is Error typeerror:object is not  a function            }        }
Chicken Ribs==

Always use only = = = and!==. Because the = = type conversion is done by default, the rules are very difficult to remember. For details of the rules see my other article JS = = Conversion rules

with

We all know that with the change of scope, in some cases it is quite convenient, but the performance problem is rather heavy. It is advisable not to use the With

Eval

The questions that Eval brings are summarized as follows:

    • Make the code harder to read
    • Significantly reduced performance
    • Not conducive to jslint tool detection problems
    • Reduced security for your application

Also similar to eval 1) function constructor 2) passing string arguments in the settimeout or SetInterval function

Try to avoid them like this.

Continue statements

The function of this command is to return to the head of the loop, but the loop will return to the head. Therefore, the use of this command can be avoided by proper construction, resulting in improved efficiency. Significant improvement in performance by refactoring to remove continue statements

switch runs through

Everyone knows that in a switch statement in JS, one case condition can penetrate into another, although this feature is very useful in some scenarios, but they are also very dangerous.

statement with missing block

It is recommended that even if there is only one statement, enclose them in the IF, while, do, or for in curly braces.

++   --

when using + + and--the code tends to become overly dense and obscure, so it is recommended not to use them as a guideline

The surface can make the code very compact, but it actually makes the code look more complex and obscure. For the sake of the cleanliness and legibility of the code, therefore not for good.

Bitwise Operators

JavaScript does not have integer types, only double-precision floating-point numbers, so bitwise operators convert their numeric operations to integers first, then perform operations and then convert back, so the bitwise operator is inefficient in JavaScript, so it is recommended to use it less.

Note:

    • There is no integer concept in JavaScript, but using good bitwise operators can be handled with ease, while gaining efficiency gains.
    • | and ~ ~ is a good example of using both to convert a floating point into an integer and to be more efficient than a similar parseint,math.round. It is useful when dealing with effects such as pixels and animation displacements.

Function statement

There are two ways to define a function in javascript:

 function foo () {}/ /First varfunction () {}/// second type 

The two formulations are completely equivalent. However, when parsing, the previous method is automatically promoted to the head of the code, thus violating the function should be defined after the use of the requirements, it is recommended to define the function, all use the latter way of writing.

Wrapper object of type

JavaScript has a type of wrapper object. Do not use the new Boolean, new number, or new String, which means

    New  String ("Hello World");   New number (+);  New Boolean (false

Also, avoid using the new object and the new Array, using {} and [] instead

New

Use new with caution and avoid polluting global objects caused by this.

In JavaScript, the class is defined like this

  var function    (name) {  this. Name = name;   this. Saying = ' Meow ' ; }

The resulting object is shown in the following code

  var New Cat (' Mimi ');

This use of functions to generate classes, using new to generate the syntax of the object, in fact, is very strange, not intuitive. Moreover, when used, it is easy to forget to add new, it will become the execution function, and then inexplicably a few more global variables. Therefore, it is recommended that you do not create objects this way, but instead use a workaround.

Douglas Crockford gives a function:

function    (o) {  varfunction= o;   returnnew  F; };

This function is used to manipulate the prototype object as it is created:

  var  Cat = {name:', saying:' meow ' };  var mycat = Object.beget (Cat);

void

In JavaScript, Void is an operator that accepts an operand and returns undefined. This command is useless and confusing, and it is recommended to avoid it.

The JavaScript dross and the ribs I know

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.