45 practical skills that JavaScript programmers should know

Source: Internet
Author: User
Tags case statement

As you know, JavaScript is the world's first programming language. It is a Web language and a language for mobile hybrid apps (such as PhoneGap or Appcelerator ), it is a server-side language (such as NodeJS or Wakanda) and has many other implementations. At the same time, it is also the first language for many new users, because it not only displays a simple alert information in the browser, but also can be used to control a robot (using nodebot or nodruino ). Developers who have mastered JavaScript and can write code with standardized organization and efficient performance have become search targets in the talent market.
It should be noted that all 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 values to a variable for the first time.
If you assign a value to an undefined variable, a global variable is created. Avoid global variables.
2-Use = instead of =
= (Or! =) The operator automatically performs type conversion when needed. = (Or! =) The operation will not perform any conversions. It compares values and types and is considered to be faster than =.
Copy codeThe Code is as follows:
[10] = 10 // is false
[10] = 10 // is true
'10' = 10 // is true
'10' = 10 // is false
[] = 0 // is true
[] = 0 // is false
''= False // is true but true =" a "is false
''= False // is false

3-use closures to implement private variables
Copy codeThe Code is as follows:
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 ;};

// Properties not initialized in the constructor
Var occupation;
This. getOccupation = function () {return occupation ;};
This. setOccupation = function (newOcc) {occupation =
NewOcc ;};
}

4-use a semicolon at the end of the statement
Using semicolons at the end of a statement is a good practice. If you forget to write it, you will not be warned, because in most cases, the JavaScript interpreter will add a semicolon to you.
5-create object constructor
Copy codeThe Code is as follows: function Person (firstName, lastName ){
This. firstName = firstName;
This. lastName = lastName;
}

Var Saad = new Person ("Saad", "Mousliki ");
6-use typeof, instanceof, and constructor with caution
Copy codeThe Code is as follows: var arr = ["a", "B", "c"];
Typeof arr; // return "object"
Arr instanceof Array // true
Arr. constructor (); // []
7-create a Self-called function (Self-calling Funtion)
This is often called Self-Invoked Anonymous Function or the IIFE-Immediately Invoked Function Expression ). This is a function that is automatically executed immediately after creation, usually as follows:
Copy codeThe Code is as follows:
(Function (){
// Some private code that will be executed automatically
})();
(Function (a, B ){
Var result = a + B;
Return result;
}) (10, 20)

8-get a random entry from the array
Copy codeThe Code is as follows: var items = [12,548, 'A', 2, 5478, 'foo', 8852, 'doe ', 2145,119];

Var randomItem = items [Math. floor (Math. random () * items. length)]; [code]
9-obtain 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.
[Code] var x = Math. floor (Math. random () * (max-min + 1) + min;
10-generate an array of numbers between 0 and the set maximum.
Copy codeCode: var numbersArray = [], max = 100;

For (var I = 1; numbersArray. push (I ++) <max;); // numbers = [100,...]
11-generate a random alphanumeric string
Copy codeThe Code is as follows: function generateRandomAlphaNum (len ){
Var rdmstring = "";
For (; rdmString. length <len; rdmString + = Math. random (). toString (36). substr (2 ));
Return rdmString. substr (0, len );
}
12-disrupt a number Array
Copy codeThe Code is as follows: var numbers = [5,458,120,-215,228,400,122 205,-85411];
Numbers = numbers. sort (function () {return Math. random ()-0.5 });
/* The array numbers will be equal for example to [120, 5,228,-215,400,458,-85411,122] */
13-String trim Function
In Java, C #, PHP, and many other languages, there is a classic trim function, which is used to remove space characters in strings, but not in JavaScript, therefore, we need to add this function to the String object.
Copy codeThe Code is as follows:
String. prototype. trim = function () {return this. replace (/^ \ s + | \ s + $/g, "") ;}; // remove the leading and trailing spaces of the string, excluding the internal spaces of the string.
14-append an array to another Array
Copy codeCode: var array1 = [12, "foo", {name: "Joe"},-2458];

Var array2 = ["Doe", 555,100];
Array. prototype. push. apply (array1, array2 );
/* Array1 will be equal to [12, "foo", {name "Joe"},-2458, "Doe", 555,100] */
// In fact, concat can directly connect two arrays, but its return value is a new array. Here is a direct change to array1

15-convert the arguments object into an array
Copy codeThe Code is as follows: var argArray = Array. prototype. slice. call (arguments );
The arguments object is a class array object, but it is not a real Array
16-verify whether the parameter is a number)
Copy codeThe Code is as follows: function isNumber (n ){
Return! IsNaN (parseFloat (n) & isFinite (n );
}
17-verify whether the parameter is an array
Copy codeThe Code is as follows: function isArray (obj ){
Return Object. prototype. toString. call (obj) = '[object Array]';
}
Note: If the toString () method is overwritten (overridden), you will not be able to get the desired result by using this technique. Or you can use:
Copy codeThe Code is as follows:
Array. isArray (obj); // This is a new array method.
If you do not use multiple frames, you can also use the instanceof method. However, if you have multiple contexts, you will get the wrong result.
Copy codeThe Code is as follows: var myFrame = document. createElement ('iframe ');
Document. body. appendChild (myFrame );

Var myArray = window. frames [window. frames. length-1]. Array;
Var arr = new myArray (a, B, 10); // [a, B, 10]

// Instanceof will not work correctly, myArray loses his constructor
// Constructor is not shared between frames
Arr instanceof Array; // false
18-obtain the maximum or minimum values in a number Array
Copy codeThe Code is as follows: var numbers = [5,458,120,-215,228,400,122 205,-85411];
Var maxInNumbers = Math. max. apply (Math, numbers );
Var minInNumbers = Math. min. apply (Math, numbers );
// Note: The Function. prototype. apply method is used to pass parameters.
19-clear an array
Copy codeCode: var myArray = [12,222,100 0];
MyArray. length = 0; // myArray will be equal to [].
20-do not use delete to delete items in an array.

Use splice instead of delete to delete an item in the array. Delete is used to replace the original items with undefined instead of deleting them from the array.

Do not use this method:
Copy codeThe Code is as follows: var items = [12,548, 'A', 2, 5478, 'foo', 8852, 'doe ', 2154,119];
Items. length; // return 11
Delete items [3]; // return true
Items. length; // return 11
/* Items will be equal to [12,548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,119] */
And use:
Copy codeThe Code is as follows: var items = [12,548, 'A', 2, 5478, 'foo', 8852, 'doe ', 2154,119];
Items. length; // return 11
Items. splice (3, 1 );
Items. length; // return 10
/* Items will be equal to [12,548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,119] */
The delete method should be used to delete an attribute of an object.
21-use length to truncate an array

Similar to the preceding method of clearing an array, we use the length attribute to truncate an array.
Copy codeCode: var myArray = [12,222,100 0, 124, 98, 10];
MyArray. length = 4; // myArray will be equal to [12,222,100 0, 124].
In addition, if you set the length of an array to a value greater than the current value, the length of the array will be changed and a new undefined item will be added. The length of an array is not a read-only attribute.
Copy codeThe Code is as follows: myArray. length = 10; // the new array length is 10
MyArray [myArray. length-1]; // undefined
22-use logic AND/OR for condition Determination
Copy codeThe Code is as follows:
Var foo = 10;
Foo = 10 & doSomething (); // equivalent to if (foo = 10) doSomething ();
Foo = 5 | doSomething (); // equivalent to if (foo! = 5) doSomething ();
Logical AND can also be used to set default values for function parameters
Copy codeThe Code is as follows:
Function doSomething (arg1 ){
Arg1 = arg1 | 10; // If arg1 is not set, Arg1 is set to 10 by default.
}
23-use the map () method to traverse items in an array
Copy codeThe Code is as follows: var squares = [1, 2, 3, 4]. map (function (val ){
Return val * val;
});
// Squares will be equal to [1, 4, 9, 16]
24-rounding a number to keep N decimal places
Copy codeThe Code is as follows: var num = 2.443242342;
Num = num. toFixed (4); // num will be equal to 2.4432
25-Floating Point Number Problem
Copy codeThe Code is as follows: 0.1 + 0.2 = 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994
Why? 0.1 + 0.2 equals 0.30000000000000004. You need to know that all JavaScript numbers are internally represented by 64-bit binary floating point numbers, which comply with the IEEE 754 standard. For more information, read this blog. You can use toFixed () and toPrecision () methods to solve this problem.
26-when using for-in to traverse the internal attributes of an object, check the attributes.

The following code snippet can avoid accessing the prototype attributes when traversing an object attribute.
Copy codeThe Code is as follows:
For (var name in object ){
If (object. hasOwnProperty (name )){
// Do something with name
}
}
27-comma Operator
Copy codeThe Code is as follows:
Var a = 0;
Var B = (a ++, 99 );
Console. log (a); // a will be equal to 1
Console. log (B); // B is equal to 99
28-Cache variables for calculation and query (calculation or querying)

For jQuery selectors, we 'd better cache these DOM elements.
Copy codeThe Code is as follows: var navright = document. querySelector ('# right ');
Var navleft = document. querySelector ('# left ');
Var navup = document. querySelector ('# up ');
Var navdown = document. querySelector ('# low ');
29-verify the parameter before calling isFinite ()
Copy codeThe Code is as follows: isFinite (0/0); // false
IsFinite ("foo"); // false
IsFinite ("10"); // true
IsFinite (10); // true
IsFinite (undifined); // false
IsFinite (); // false
IsFinite (null); // true !!!
30-avoid the negative index (negative indexes) in the array)
Copy codeThe Code is as follows: var numbersArray = [1, 2, 3, 4, 5];
Var from = numbersArray. indexOf ("foo"); // from is equal to-1
NumbersArray. splice (from, 2); // will return [5]
Make sure that the parameters when indexOf is called are not negative.

31-JSON-based serialization and deserialization (serialization and deserialization)
Copy codeCode: var person = {name: 'saad', age: 26, department: {ID: 15, name: "R & D "}};
Var stringFromPerson = JSON. stringify (person );
/* StringFromPerson is equal to "{" name ":" Saad "," age ": 26," department ": {" ID ": 15," name ": "R & D "}}"*/
Var personFromString = JSON. parse (stringFromPerson );
/* PersonFromString is equal to person object */
32-avoid using eval () and Function Constructors
Using eval and Function constructor is very expensive because every time they call the script engine to convert source code into executable code.
Copy codeCode: var func1 = new Function (functionCode );
Var func2 = eval (functionCode );
33-avoid using ()
With (), a global variable is inserted. Therefore, variables with the same name will be overwritten, causing unnecessary trouble.
34-avoid using for-in to traverse an array
Avoid using this method:
Copy codeThe Code is as follows: var sum = 0;
For (var I in arrayNumbers ){
Sum + = arrayNumbers [I];
}
The better way is:
Copy codeThe Code is as follows: 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 variables are executed only once, which is more efficient than the following method:
Copy codeThe Code is as follows: for (var I = 0; I <arrayNumbers. length; I ++)
Why? Because arrayNumbers. length is calculated every time it is cyclically.
35-input a function when calling setTimeout () and setInterval () instead of a string.
If you pass the string to setTimeout () or setInterval (), the string will be parsed like eval, which is very time-consuming.
Do not use:
Copy codeThe Code is as follows:
SetInterval ('dosomethingperiodically () ', 1000 );
SetTimeOut ('dosomethingafterfiveseconds () ', 5000)
Usage:
Copy codeThe Code is as follows:
SetInterval (maid, 1000 );
SetTimeOut (doSomethingAfterFiveSeconds, 5000 );
36-use the switch/case statement instead of a long string of if/else
When there are more than two conditions, the use of switch/case is more efficient and more elegant (easier to organize code ). However, do not use switch/case when there are more than 10 cases.
37-use switch/case when determining the value range
In the following case, it is reasonable to use switch/case to determine the value range:
Copy codeThe Code is as follows:
Function getCategory (age ){
Var category = "";
Switch (true ){
Case isNaN (age ):
Category = "not an age ";
Break;
Case (age> = 50 ):
Category = "Old ";
Break;
Case (age <= 20 ):
Category = "Baby ";
Break;
Default:
Category = "Young ";
Break;
};
Return category;
}
GetCategory (5); // will return "Baby"
// Generally, if/else is suitable for determining the value range. Switch/case is more suitable for determining the value
38-specify a prototype object for the created object
It is possible to write a function to create an object with the specified parameter as prototype:
Copy codeThe Code is as follows: function clone (object ){
Function OneShotConstructor (){};
OneShotConstructor. prototype = object;
Return new OneShotConstructor ();
}
Clone (Array). prototype; // []
39-an HTML Escape Function
Copy codeThe Code is as follows: function escapeHTML (text ){
Var replacements = {"<": "<", ">": "> ","&":"&","\"":"""};
Return text. replace (/[<> & "]/g, function (character ){
Return replacements [character];
});
}
40-avoid using try-catch-finally within the loop
During runtime, when the catch clause is executed, the caught exception object is assigned a variable, and this variable is created every time in the try-catch-finally structure.

Avoid writing like this:
Copy codeThe Code is as follows: var object = ['foo', 'bar'], I;
For (I = 0, len = object. length; I <len; I ++ ){
Try {
// Do something that throws an exception
}
Catch (e ){
// Handle exception
}
}
And use:
Copy codeThe Code is as follows: var object = ['foo', 'bar'], I;
Try {
For (I = 0, len = object. length; I <len; I ++ ){
// Do something that throws an exception
}
}
Catch (e ){
// Handle exception
}
41-set timeout for XMLHttpRequests.
After an 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 XHR calls ().
Copy codeThe Code is as follows: var xhr = new XMLHttpRequest ();
Xhr. onreadystatechange = function (){
If (this. readyState = 4 ){
ClearTimeout (timeout );
// 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 ();
In addition, you should avoid synchronous Ajax requests.
42-processing WebSocket timeout
Generally, after a WebSocket connection is created, if you are not active, the server will disconnect you 30 seconds later. The firewall also disconnects after a period of inactivity.

To prevent timeout, you may need to send an empty message intermittently to the server. To do this, you can add the following two functions in your code: one to maintain the connection and the other to cancel the connection. With this technique, you can control timeout issues.

Use a timerID:
Copy codeCode: 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 connected to webSOcket, while cancelKeepAlive () should be added at the end of the onClose () method.
43-keep in mind that the original operators are always more efficient than function calls. Use VanillaJS.
For example, do not use:
Copy codeThe Code is as follows: var min = Math. min (a, B );
A. push (v );
Usage:
Copy codeThe Code is as follows: var min = a <B? A B;
A [A. length] = v;
44-do not forget to use the neat code tool when coding. Use JSLint and code compression tool (minification) (such as JSMin) before going online ). Saving time: Code beautification and formatting tools

45-JavaScript is incredible.

Summary

I know that there are many other tips, tips, and best practices. If you have any other feedback or corrections you want to add or share with me, Please comment out in the comments.

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.