68 effective ways of writing high-quality JavaScript code

Source: Internet
Author: User
Tags readable variable scope

1th Chapter Make yourself accustomed to JavaScript

1th: understand the JavaScript version you use

Decide which versions of JavaScript your application Supports.

Make sure that the JavaScript features you use are supported for all environments that your application will Run.

2nd: Understanding the floating-point number of JavaScript

The numbers in JavaScript are stored as a double-precision 64-bit floating-point number, whereas JavaScript integers are only a subset of the double-precision floating-point numbers, not individual data types. The addition of decimals and decimals is sometimes inaccurate, and if you use it as a monetary calculation, it is best to convert it to the smallest currency.

3rd: Beware of implicit casts

In javascript, What do you think of the result of "3+true"? yes, It's 4!

The plus sign can be used either for addition or for string joins, and what the operation depends on its parameter type. therefore, in the calculation often accompanied by implicit conversion, especially need to pay attention to.

Judging is not the number, with isnan? This is not necessarily a reliable. fortunately, there is a simple and efficient way to detect whether a value is Nan or not, as with itself. For example "a!== a".

Tests whether a value is an undefined value, compares it with the TypeOf method or undefined instead of using the truth Operation.

4th: the original type takes precedence over the encapsulated object

As a comparison, the encapsulated object of the original type behaves differently from its original Value. The approximate meaning is that the direct "hello" string and the var a = new string ("hello") are not equal, the former is the original type, and the latter is an object.

5th: Avoid using the = = Operator for mixed types

When the parameter type is not the same, the = = operator applies a set of implicit cast rules that are difficult to understand. So it is good to always use = = =, It does not produce any implicit conversions.

6th: Understanding the limitations of semicolon insertion

All in all, try not to be graceful or forget the code, remember to add a semicolon at the end of the statement, and do not rely on Javascript's auto-insertion semicolon Technology.

7th: sequence of code elements with a 16-bit view string

The JavaScript string consists of 16-bit code units, not a Unicode code Point. It's good to know, but don't delve into it for the time Being.

2nd Chapter Variable Scope

8th: use as few global objects as possible

Try to avoid using global variables, and use local Variables. Also avoid adding properties to global Objects.

9th: always declare local variables

Something more troublesome than a global object is an unexpected global variable. So always declare a new local variable with var.

10th: Avoid using with

11th: Master Closure

Closures are one of the most elegant and expressive features of JavaScript and are at the heart of many idiomatic usages, so understanding closures is particularly important.

Closures can reference variables that define their outer scopes.

Closures have a longer life cycle than the functions that create Them.

Closures internally store references to their external variables and can read and write these Variables.

12th: Understanding Variable Declaration Promotion

Declared variables in a code block are implicitly promoted to the top of the enclosing Function.

A re-declaration is treated as a single variable.

You can consider manually promoting local variable declarations to avoid Confusion.

13th: Create a local variable using the Call function expression (iife) immediately

Understand the difference between binding and Assignment.

Closures capture their external variables by reference rather than by Value.

14th: beware of naming functions to express awkward scopes

15th: Beware of local block function declarations awkward scopes

Always place a function declaration at the outermost layer of a program or contained function to avoid the non-portable Behavior.

Replace a conditional function declaration with a VAR declaration and a conditional assignment statement.

16th: Avoid using eval to create local variables

17th: an indirect call to the Eval function is better than a direct call

The 3rd chapter uses the function

18th: Understanding the differences between function calls, method calls, and constructor calls

A function call takes a global object as its Recipient. This method of invocation is seldom used in general.

The method call will be the object of the Lookup method property as the calling Recipient.

The constructor call is called through the new operator and produces a new object as the Receiver.

19th: Master High-order functions

Higher-order functions are those functions that use functions as parameters or return Values.

20th: use the call method to customize the recipient to invoke the method

Use the call method to invoke a method that does not exist in the given Object.

21st: use the Apply method to call the function with different number of parameters

22nd: use arguments to create a variable parameter function

23rd: never modify the arguments object

We can use a technique similar to "var arg = Array.slice.call (arguments)" to invoke the array method, by copying the object into a real array and modifying it.

24th: use variables to save arguments references

Binds an explicit scope reference to the arguments variable so that it can be referenced in a nested Function.

25th: using the Bind method to extract a method with a definite receiver

It is important to note that extracting a method does not bind the receiver of the method to the object of the Method.

Use the Bind method to create a function that binds to the appropriate receiver.

26th: using the Bind method to implement the function currying

Pass in null or undefined as the Receiver's parameter to implement the function curry, thus ignoring its receiver.

27th: encapsulate code using closures instead of strings

28th: do not trust the function object ToString method

In general, you should avoid using the ToString method of a function Object.

29th: Avoid using non-standard stack check properties

In short, avoiding the use of the Arguments.callee and Arguments.caller methods, These two non-standard methods do not have good Portability.

Chapter 4th objects and prototypes

30th: Understanding the difference between prototype, getprototypeof and __proto__

The C.prototype property is a prototype of the object created by new C ().

Object.getprototypeof (obj) is the standard function for retrieving object prototypes in ES5.

Obj.__proto__ is a non-standard method for retrieving object Prototypes.

A class is a design pattern that consists of a constructor and an associated Prototype.

31st: Use the object.getprototypeof function instead of using __proto__

32nd: always do not modify the __proto__ property

33rd: make the constructor independent of the new operator

Calling itself in the constructor definition by using the new operator or the Object.create () method makes the constructor independent of the calling Syntax.

When a function expects to be called with the new operator, the function is clearly documented.

34th: storing methods in prototypes

Storing a method in an instance object creates multiple copies of the function, because each instance object has a Copy.

Storing a method in a prototype is better than storing it in an instance Object.

35th: use closures to store private data

The closure variable is private and can only be obtained by a local reference.

Use local variables as private data to implement information hiding through METHODS.

36th: Store the instance state only in the instance object

Sharing mutable data can be problematic because the prototype is shared by all of its instances.

Stores a mutable instance state in an instance Object.

37th: recognize the implicit binding problem of this variable

The scope of the this variable is always determined by its nearest enclosing Function.

Use a local variable (usually named self, me, or That) to make the this binding available for intrinsic functions.

38th: call the constructor of the parent class in the constructor of the subclass

The parent class constructor is called explicitly in the subclass constructor, which is passed as an explicit recipient.

Use the Object.create function to construct a prototype object of a subclass to avoid calling the constructor of the parent class.

39th: do not reuse the property name of the parent class

40th: avoid inheriting the standard class

41st: See prototypes as Implementation details

An object is an interface, and a prototype is an Implementation.

42nd: Avoid using rash monkey patches

Monkey patch means that because objects share a prototype, each object can add, delete, and modify the properties of the Prototype.

5th chapter Arrays and Dictionaries

43rd: Constructing a lightweight dictionary using a direct instance of object

The lightweight dictionary should be a direct subclass of Object.prototype to make the for ... In cycles from prototype Contamination.

44th: use NULL prototypes to prevent prototype contamination

45th: use the hasOwnProperty method to avoid prototype contamination

46th: storing an ordered collection using an array instead of using a dictionary

Using the for...in loop to enumerate object properties should be independent of order.

47th: never add an enumerable property to the Object.prototype

If you are sure you want to add properties to object.prototype, use the Object.defineproperty method in ES5 to define them as non-enumerable Properties.

48th: avoid modifying objects during enumeration

When you use the for...in loop to enumerate the properties of an object, make sure that you do not modify the Object.

When iterating over an object, if the Object's contents may be changed during the loop, you should use the while or for loop instead of the for...in loop.

49th: array iterations should prefer a for loop instead of a for...in loop

Consider storing the length of the array in a local variable before the loop to avoid recalculating the array length.

50th: iterative methods are better than loops

Replacing A For loop with an iterative method, such as Array.prototype.forEach or Array.prototype.map, makes the code more readable and avoids repeating the loop control Logic.

It is recommended that you use a traditional loop in case you need to terminate the cycle prematurely.

51st: reusing a common array method on a class array object

Any object that has an indexed property and an appropriate length property can use the universal array Method.

52nd: array literals are better than array constructors

6th Chapter Library and API design

53rd: to maintain a consistent agreement

Using a consistent convention in variable naming and function signing

54th: treat undefined as "no value"

Avoid using undefined to represent any non-specific Value.

Use a descriptive string or an object that names a Boolean property instead of using undefined or null to represent a specific app Flag.

The default value for the supplied parameter should be the test undefined instead of checking the Arguments.length.

In a place where 0, nan, or an empty string is a valid parameter, you should never implement a parameter default value by using a truth Test.

55th: the option object that accepts the keyword parameter

Using option objects makes the API more readable and easier to remember.

56th: Avoid unnecessary state

Use the stateless API as much as you Can. (such as "foo". touppercase is always "foo", then this is stateless; and date () corresponds to the Variable)

If the API is stateful, identify which states are associated with each Operation.

57th: design Flexible interfaces using structure type (duck Type)

58th: distinguish between array objects and class array objects

59th: Avoid excessive forced conversions

60th: Support Method Chain

Part of the functionality of stateless APIs is the flexibility to break down complex operations into smaller operations.

Use the method chain to connect stateless Operations.

Supports a method chain by returning a new object in a stateless method.

The method chain is supported by returning this in a stateful method.

7th Chapter Concurrency

61st: do not block the I/O time queue

Asynchronous APIs use callback functions to slow down processing expensive operations to avoid blocking the main application

JavaScript receives time concurrently, but uses an event queue to process the event handlers Sequentially.

Never use blocked I/O in the application event Queue.

62nd: using nested or named callback functions in an asynchronous sequence

Executes multiple asynchronous operations sequentially, using nested or named callback Functions.

Try to strike a balance between too many nested callback functions and awkward named Non-nested callback Functions.

Avoid sequencing operations that can be executed in parallel.

63rd: Beware of discarding errors

Avoid copying and pasting error-handling code by writing shared error-handling Functions.

Be sure to handle all error conditions explicitly to avoid discarding errors.

64th: recursive use of asynchronous loops

Loops are not asynchronous.

Use recursive functions to perform iterations in a separate utterly of the event loop.

Recursion is performed in a separate turn in the event loop and does not cause the call stack to OVERFLOW.

65th: do not block the event queue when calculating

Avoid executing expensive algorithms in the main event Queue.

66th: use counters to perform parallel operations

The occurrence of events in a JavaScript application is indeterminate, that is, the order is Unpredictable.

Use counters to avoid data contention in parallel operations.

67th: never substitute asynchronous callback functions synchronously

Never call an asynchronous callback function synchronously, even if you can get the data immediately.

Calling asynchronous callback functions synchronously disrupts the action sequence of the tone and may lead to unexpected interleaved code.

Calling asynchronous callback functions synchronously can cause the stack to overflow or incorrectly handle the Exception.

Use asynchronous apis, such as the settimeout function, to dispatch an asynchronous callback function to run it in another round.

68th: clean asynchronous logic with promise mode

The promise represents the final value, which is the final effect when the parallel operation is Completed.

Use promise to combine different parallel operations.

Use Promise-mode APIs to avoid data Contention.

Use select (also known as Choose) when an intentional race condition is Required.

68 effective ways of writing high-quality JavaScript code

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.