JavaScript is the world's first programming language, the language of the web, the language of mobile hybrid apps (such as PhoneGap or Appcelerator), the server-side language (such as Nodejs or Wakanda), and has many other implementations. It is also an enlightening language for many novices, as it can not only display a simple alert message on the browser, but also can be used to control a robot (using Nodebot, or Nodruino). Developers who master JavaScript and can write code that is well-organized and performance-efficient have become hunters in the talent market.
In this article, I'll share a set of JavaScript tips, tricks, and best practices that JavaScript programmers should be aware of, whether they're using a browser/engine or a server-side (Ssjs--service Side JavaScript) on the JavaScript interpreter.
Translator Note: The original author wrote a total of 44 (missing the 3rd article), the translator himself to fill a thought more important skills.
Note that the code snippets in this article have been tested on the latest Google Chrome (version 30), which uses the V8 JavaScript engine (V8 3.20.17.15)
1. Do not forget to use the var keyword when assigning a value to a variable for the first time
Assigning a value to an undefined variable causes a global variable to be created. To avoid global variables.
2. Use = = = instead of = =
the = = (or! =) operator automatically performs type conversions when needed. the = = = (or!==) operation does not perform any conversions. It compares values and types, and is considered better at speed than = =.
[ten] = = = //is false[10] = =//is true ' = =/ /is true ' = = = =//is false [] = = 0
//is true [] = = 0 //is false "= = False //is true but true = =" A "is false" = = = false/*is Fals e*/
3. Using closures to implement private variables (translator add)
function person (name, age) { this.getname = function () {return name;}; This.setname = function (newName) {name = NewName;}; This.getage = function () {return age;}; This.setage = function (newage) {age = NewAge;}; Property that is not initialized in the constructor var occupation; This.getoccupation = function () {return occupation;}; This.setoccupation = function (NEWOCC) {occupation = newocc;};}
4. Use semicolons at the end of the statement
Using semicolons at the end of a statement is a good practice. If you forget to write you will not be warned, because in most cases the JAVASCRIPT interpreter will help you to add semicolons.
5. Create a constructor for an object
function person (firstName, lastName) { this.firstname = firstName; This.lastname = LastName;} var Saad = new Person ("Saad", "Mousliki");
6. Use typeof, instanceof and constructor with care
var arr = ["A", "B", "C"];typeof arr; Return "Object" arr instanceof Array//Truearr.constructor (); /*[]*/
7. Create a self-calling function (self-calling Funtion)
This is often referred to as a self-invocation of an anonymous function (self-invoked Anonymous function) or an instant call to a functional expression (iife-immediately invoked functions expressions). This is a function that is automatically executed immediately after creation, usually as follows:
(function () { ///Some private code that would be executed automatically}) ();(function (A, b) { var result = A+b; return result;}) (10,20)
8. Get a random item from an array
var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2145, 119];var randomitem = Items[math.floor (Math.ran Dom () * items.length)];
9. Get a random number within a specific range
This code snippet is useful when you want to generate test data, such as a random salary value between the minimum and maximum values.
var x = Math.floor (Math.random () * (Max-min + 1)) + min;
10. Generate a numeric array between 0 and the maximum value set
var numbersarray = [], max = 100;for (var i=1; Numbersarray.push (i++) < Max;);//numbers = [0,1,2,3 ... 100]
11. Generate a random alphanumeric string
function Generaterandomalphanum (len) { var rdmstring = ""; for (; rdmstring.length < Len; rdmstring + = Math.random (). toString (. substr (2)); return rdmstring.substr (0, Len);}
"Translator Note: deliberately checked math.random () generates random numbers from 0 to 1, number.tostring (36) Converts this number to 36 (0-9,a-z), and finally ' substr removes the preceding ' 0. ' String
12. Scrambling a numeric array
var numbers = [5, 458, -215, 228, 122205, -85411];numbers = Numbers.sort (function () {return math.random ()- 0.5});/* The array numbers would be equal for example to [5, 228, -215, 458, 122205, -85411,] */
The trim function of string
There is a classic trim function in Java, C #, PHP, and many other languages to remove the whitespace from the string, not in JavaScript, so we need to add this function to the string object.
String.prototype.trim = function () {return this.replace (/^s+|s+$/g, "");};
14. Attach (append) an array to another array
var array1 = [N, "foo", {name: "Joe"}, -2458];var array2 = ["Doe", 555, 100]; Array.prototype.push.apply (Array1, array2);/* Array1 'll is equal to [N, "foo", {name "Joe"}, -2458, "Doe", 555 , 100] */
Note: In fact, concat can directly implement the connection of two arrays, but its return value is a new array. Here is a direct change array1
15. Converting a arguments object to an array
var Argarray = Array.prototype.slice.call (arguments);
Translator Note: The arguments object is a class array object, but not a real array
16. Verify that the parameter is numeric (number)
function Isnumber (n) { return!isnan (parsefloat (n)) && isfinite (n);}
17. Verify that the parameter is an array
function IsArray (obj) { return Object.prototype.toString.call (obj) = = = ' [Object Array] ';}
Note: If the toString () method is rewritten (overridden), you will not get the desired result with this technique. Or you can use:
Array.isarray (obj); This is the method of a new array
If you are not using multiple frames, you can also use the Instanceof method. But if you have multiple contexts, you will get the wrong result.
var myframe = document.createelement (' iframe ');d ocument.body.appendChild (myframe); var myArray = window.frames[ WINDOW.FRAMES.LENGTH-1]. Array;var arr = new MyArray (a,b,10); [a,b,10]//instanceof won't work correctly, MyArray loses he constructor//constructor is not shared between frames Arr instanceof Array; False
18. Get the maximum or minimum value in a numeric array
var = [5, 458, -215, 228, Numbers, 122205, -85411];var maxinnumbers = Math.max.apply (Math, numbers); var Mininnumbers = Math.min.apply (Math, numbers);
Note: Here are the techniques for passing parameters using the Function.prototype.apply method
19. Empty an array
var myArray = [222,];myarray.length = 0; MyArray'll is equal to [].
20. Do not use Delete to delete an item in an array.
Use splice instead of Delete to remove an item from the array. Using delete simply replaces the original item with undefined, not the actual deletion from the array.
Do not use this method:
var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];items.length; return 11delete items[3]; return trueitems.length; Return 11/* items equal to [548, "a", undefinedx1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119 ] */
Instead, use:
var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];items.length; Return 11items.splice (3,1); items.length; Return 10/* items equal to [548, "a", 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119] */
The Delete method should be used to delete a property of an object.
21. Use length to truncate an array
Similar to the way we emptied the array above, we use the Length property to truncate an array.
var MyArray = [N, 222, +, 124, 98,];myarray.length = 4; MyArray'll is equal to [12, 222, 1000, 124].
In addition, if you set the length of an array to a value larger than the current size, then this array will be changed to add a new undefined. The length of the array is not a read-only property.
Myarray.length = 10; The new array length is 10myarray[myarray.length-1]; Undefined
22. Using logical and/or to make conditional judgments
var foo = 10;foo = = && dosomething (); Equivalent to if (foo = =) dosomething (); foo = = 5 | | DoSomething (); Equivalent to if (foo! = 5) dosomething ();
Logical and can also be used to set default values for function parameters
function DoSomething (arg1) { Arg1 = arg1 | | 10;//If Arg1 is not set, ARG1 will be set to 10} by default
23. Use the map () method to iterate through an array of items
var squares = [1,2,3,4].map (function (val) { return val * val;}); /squares'll be equal to [1, 4, 9, 16]
24. Rounding a number, preserving n decimal places
var num =2.443242342;num = num.tofixed (4); num'll be equal to 2.4432
25– floating point problem
0.1 + 0.2 = = = 0.3//is false9007199254740992 + 1//are equal to 90071992547409929007199254740992 + 2//are equal to 90071 99254740994
Why is that? 0.1+0.2 equals 0.30000000000000004. You know, all of the JavaScript numbers are internally floating numbers in 64-bit binary notation, conforming to the IEEE 754 standard. For more information, you can read this blog post. You can use the toFixed () and Toprecision () methods to solve this problem.
26. When using For-in to traverse an object's internal properties, be careful to check the properties
The following code snippet avoids accessing the properties of a prototype while traversing an object property
for (var name in object) { if (Object.hasownproperty (name)) { //does something with name }}
27. Comma operator
var a = 0;var B = (a++); Console.log (a); A'll is equal to 1console.log (b); B is equal to 99
28. Cache variables that need to be computed and queried (calculation or querying)
For jquery selectors, we'd better cache these DOM elements.
var navright = document.queryselector (' #right '), var navleft = document.queryselector (' #left '); var navup = Document.queryselector (' #up '); var navdown = Document.queryselector (' #down ')
29. Verify the parameters before calling Isfinite ()
Isfinite (0/0); Falseisfinite ("foo"); Falseisfinite ("10"); Trueisfinite (ten); Trueisfinite (undifined); Falseisfinite (); Falseisfinite (null); True !!!
30. Avoid negative indexes in the array (negative indexes)
var numbersarray = [1,2,3,4,5];var from = Numbersarray.indexof ("foo"); From is equal To-1numbersarray.splice (from,2); would return [5]
Ensure that the parameter when calling IndexOf is not a negative number.
31. JSON-based serialization and deserialization (serialization and deserialization)
var person = {name: ' Saad ', age:26, department: {id:15, Name: "R & R"}};var Stringfromperson = Json.stringify (per son);/* Stringfromperson is equal to ' {' name ': ' Saad ', ' age ': ', ' Department ': {' ID ': ' Name ': ' R '}} ' */var personfromstring = Json.parse (Stringfromperson);/* personfromstring is equal to Person object */
32. Avoid using the eval () and function constructors
Using the Eval and function constructors is a very expensive operation because each time they invoke the scripting engine to convert the source code into executable code.
var func1 = new Function (functioncode), var func2 = eval (functioncode);
33. Avoid using with ()
using with () inserts a global variable. Therefore, a variable of the same name will be overwritten with the value causing unnecessary trouble.
34. Avoid using for-in to traverse an array
Avoid the use of this method:
var sum = 0;for (var i in arraynumbers) { sum + = Arraynumbers[i];}
The Better Way is:
var sum = 0;for (var i = 0, len = arraynumbers.length; i < Len; i++) {sum + = arraynumbers[i];}
The additional benefit is that the values of the I and Len two variables are executed only once and are more efficient than the following:
for (var i = 0; i < arraynumbers.length; i++)
Why? Because arraynumbers.length is calculated every time the loop is cycled.
35. When calling SetTimeout () and SetInterval (), pass in the function instead of the string.
If you pass the string to SetTimeout () or setinterval (), the string will be parsed as if it were using eval, which is very time consuming. Do not use:
SetInterval (' dosomethingperiodically () ', +); SetTimeOut (' Dosomethingafterfiveseconds () ', 5000)
Instead, use:
- SetInterval(dosomethingperiodically, +);
- SetTimeOut(dosomethingafterfiveseconds, );
36. Use the Switch/case statement instead of a long string of if/else
Using Switch/case is more efficient and more elegant (easier to organize code) when judging more than 2 kinds of things. But do not use switch/case when judging more than 10 kinds of situations.
37. Use Switch/case when judging the range of values
In this case, it is reasonable to use switch/case to determine the range of values:
function GetCategory (age) { var category = ""; Switch (true) {case IsNaN: category = ' not ' age '; break; Case (age >=): category = ' old '; break; Case (age <=): Category = "Baby"; Break Default:category = "Young"; Break }; return category; } getcategory (5); would return "Baby"
Translator Note: Generally for the value range of judgment, with If/else will be more appropriate. Switch/case is more suitable for determining the numerical value
38. Specify the prototype object for the created object
It is possible to write a function to create an object with the specified parameters as prototype:
function Clone (object) { function Oneshotconstructor () {}; Oneshotconstructor.prototype= object; return new Oneshotconstructor ();} Clone (Array). prototype; // []
39. An HTML escape function
function escapehtml (text) { var replacements= {"<": "<", ">": ">", "&": "&", "" ":" "}; Return Text.replace (/[<>& "]/g, function (character) { return replacements[character]; });}
40. Avoid using try-catch-finally inside the loop
At run time, each time a catch clause is executed, the caught exception object is assigned to a variable, and in the try-catch-finally structure, the variable is created each time. Avoid such a writing:
var object = [' foo ', ' Bar '], i;for (i = 0, len = object.length; I <len; i++) { try { //do something this throw S an exception } catch (e) { //Handle exception }}
Instead, use:
var object = [' foo ', ' Bar '], i;try {for (i = 0, len = object.length; I <len; i++) { //does something that thr oWS an exception }}catch (e) {/ * handle exception*/}
41. Set the timeout for xmlhttprequests.
After a XHR request takes a long time (for example, due to network problems), you may need to abort this request, so you can use SetTimeout () for the XHR call. Also, generally you should avoid synchronous Ajax requests altogether.
var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () { if (this.readystate = = 4) { cleartimeout (ti Meout); Do something with response data }}var timeout = setTimeout (function () { xhr.abort ();//Call Error callback}, 60*1000/* Timeout after a minute */); Xhr.open (' GET ', url, true); Xhr.send ();
42. Handling WebSocket Timeouts
Typically, after a WebSocket connection is created, if you do not have an activity, the server disconnects (time out) your connection after 30 seconds. The firewall will also disconnect after a period of inactivity.
To prevent timeouts, you may need to intermittently send an empty message to the server side. To do this, you can add the following two functions to your code: one to keep the connection and the other to cancel the connection. With this technique, you can control the problem of timeouts.
Use a Timerid:
var Timerid = 0;function keepAlive () { var timeout = 15000; if (websocket.readystate = = Websocket.open) { websocket.send ("); } Timerid = setTimeout (keepAlive, timeout);} function cancelkeepalive () { if (timerid) { canceltimeout (Timerid); }}
The KeepAlive () method should be added at the end of the OnOpen () method of the WebSocket connection, and cancelkeepalive () is added at the end of the OnClose () method.
43. Keep in mind that primitive operators are always more efficient than function calls. Use Vanillajs.
For example, do not use:
var min = Math.min (A, b); A.push (v);
Instead, use:
var min = a < b? A b; A[a.length] = v;
44. Do not forget to use the Code neat tool when coding. Use the JSLint and code compression tools (Minification) (such as jsmin) before you go live. JavaScript is incredible.
Practical JavaScript tips, tricks, and best practices