JavaScript is a world-leading programming language for Web development, mobile application development (PHONEGAP, Appcelerator), server-side development (node. js and Wakanda), and more. JavaScript is also the first language for many beginners to step into the programming world. It can be used to display a simple cue box in a browser or to control a robot by Nodebot or Nodruino. Developers who can write well-structured, performance-efficient JavaScript code are now the most sought after in the recruiting market.
In this article, you'll share some JavaScript tips, tricks, and best practices that apply, with the exception of a few, whether it's a browser's JavaScript engine or a server-side JavaScript interpreter.
The sample code in this article has been tested on the latest version of Google Chrome 30 (V8 3.20.17.15).
1 Make
sure to use the var keyword when assigning a variable for the first time
Variables are not declared and are directly assignable, and as a new global variable by default, avoid using global variables as much as possible.
2
Use = = = = = =
The = = and! = operators automatically convert data types when needed. but = = = and!== do not, they compare values and data types at the same time, which makes them faster than = = and! =.
3
underfined, NULL, 0, False, NaN, empty string logical result is False
underfined, NULL, 0, False, NaN, empty string have logical results of false
4
end of line using semicolons
In practice it is best to use a semicolon, forget to write it is OK, most of the case the JavaScript interpreter will be automatically added. For reasons to use semicolons, refer to the article JavaScript for the truth about semicolons.
5
using the object Builder
6
Use typeof, Instanceof and contructor with caution
The Typeof:javascript unary operator, which returns the original type of the variable as a string, note that typeof null also returns object, and most of the object types (array arrays, time date, and so on) also return an object
Contructor: Internal prototype properties, which can be overridden by code
The instanceof:javascript operator, which is searched in the constructor in the prototype chain, returns true if found, otherwise false
7
using the self-calling function
Functions are executed automatically after they are created, often referred to as self-invoking anonymous functions (self-invoked Anonymous function) or directly calling function expressions (Immediately invoked functions expression). The format is as follows:
8
Getting members randomly from an array
9
Gets the random number in the specified range
This feature has a special number when generating false data for testing, such as the number of wages in a given range.
generates a numeric array from 0 to a specified value
generate a random alphanumeric string
The order of the number array is scrambled
The JavaScript built-in array sorting function is used here, and a better approach is to implement it with specialized code (such as the Fisher-yates algorithm), which can be found in the discussion on StackOverflow.
string to go to space
Languages such as Java, C #, and PHP implement specialized string de-whitespace functions, but there is no JavaScript in which you can use the following code to function as a trim function for a string object:
The new JavaScript engine already has a native implementation of trim ().
append between arrays
A.
object is converted to an array
Verify if it is a number
to
verify whether the array
But if the ToString () method is rewritten, it won't work. You can also use the following methods:
If you do not use a frame in your browser, you can also use instanceof, but if the context is too complex, there may be an error.
gets the maximum and minimum values in the array
empty array
do not delete or remove elements directly from the array
If you use delete directly on an array element, it is not actually deleted, just the element is set to undefined. array element deletions should use splice.
Avoid:
Instead, you should:
You can use delete when you delete an object's properties.
Use the Length property to truncate an array
The previous example empties the array with the length property, which is also used to truncate the array:
At the same time, if you make the length property larger, the value of the array will increase, and the undefined will be used as the new element fill. Length is a writable property.
use logic with or in conditions
Logic or can also be used to set default values, such as default values for function parameters.
the map () function method is used to loop the data
the
specified number of decimal digits is reserved
Note that tofixec () returns a string, not a number.
problems with floating point calculations
Why is it? Because 0.1+0.2 equals 0.30000000000000004. JavaScript numbers are built on the IEEE 754 standard and are internally represented by 64-bit floating-point decimals, as described in how numbers in JavaScript are encoded.
You can solve this problem by using tofixed () and toprecision ().
The properties of the object are checked through the for-in loop
The following usage can prevent the iteration from entering the object's prototype properties.
comma operator
temporary storage of variables for calculations and queries
In the jquery selector, you can temporarily store the entire DOM element.
Check the parameters of incoming isfinite () in advance
Avoid using negative numbers in arrays to index
Note that the index parameter passed to splice is not a negative number, and when it is negative, the element is removed from the end of the array.
serialization and deserialization using JSON
do not use eval () or function constructor
The cost of Eval () and the function constructor (Functionconsturctor) is large, and each invocation of the JavaScript engine translates the source code into executable code.
Avoid using with ()
using with () allows you to add variables to the global scope, so if there are other variables of the same name, one is easily confused and the values are overwritten.
do not use for-in with arrays
Avoid:
But:
Another benefit is that I and Len two variables are in the first declaration of the For Loop, and they are initialized only once, which is faster than this:
use functions instead of strings when passed to SetInterval () and settimeout ()
If passed to SetTimeout () and SetInterval () a string, they will be converted in a similar way to Eval, which will certainly be slower, so do not use:
Instead, use:
use Switch/case instead of a large stack of If/else
It is faster to use switch/case when judging more than two branches, but also more elegant, more conducive to the organization of the Code, of course, if there are more than 10 branches, do not use Switch/case.
The use of digital range in Switch/case
In fact, the case condition in Switch/case can also be written like this:
use objects as prototypes of objects
This allows you to create a new object that is prototyped with the given object as a parameter:
the
HTML field conversion function
do not use try-catch-finally inside the loop
The catch section in Try-catch-finally assigns an exception to a variable when it is executed, which is constructed as a new variable within the runtime scope.
Avoid:
Instead, you should:
Note Setting timeout when using xmlhttprequests
XMLHttpRequests at execution time, when there is no response for a long time (such as a network problem, etc.), the connection should be aborted and the work can be done through settimeout ():
It is also important to note that you should not initiate multiple xmlhttprequests requests at the same time.
timeout for websocket processing
Typically, after a websocket connection is created, if there is no activity within 30 seconds, the server will time out the connection, and the firewall can time out the connection with no active connections for the unit cycle.
To prevent this from happening, you can send an empty message to the server at a certain time. You can implement this requirement by using these two functions, one for keeping the connection active and the other for ending the state.
The keepAlive () function can be placed on the last side of the OnOpen () method of the WebSocket connection, and cancelkeepalive () is placed at the very end of the OnClose () method.
Time note primitive operators are faster than function calls, using Vanillajs
For example, generally don't do this:
This can be replaced by:
Note The code structure during development, check and compress JavaScript code before you go online
Don't forget to use a code beautification tool when writing code. Use JSLint (a grammar checker) and compress the code (for example, using jsmin) before you go online. Note: Code compression is now generally recommended UGLIFYJS (HTTPS://GITHUB.COM/MISHOO/UGLIFYJS2)
JavaScript is profound, there are some good learning resources
Code Academy Resources: Http://www.codecademy.com/tracks/javascript
Eloquent javascript:http://eloquentjavascript.net/written by Marjin Haverbekex
The advanced javascript:http://ejohn.org/apps/learn/written by John Resig
45 Tips for JavaScript development