45 JavaScript programming considerations and tips _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces 45 JavaScript programming notes and tips. In this article, I will share some JavaScript skills, tips, and best practices, except for a few, both the browser's JavaScript engine and the server-side JavaScript interpreter are applicable. If you need JavaScript, refer to JavaScript as a global programming language, it can be used for Web development, mobile application development (PhoneGap, Appcelerator), and server-side development (Node. js and Wakanda. JavaScript is the first language in the programming world for many new users. It can be used to display a simple prompt box in the browser, or to control the robot through nodebot or nodruino. Developers who can write JavaScript code with clear structures and high performance have become the most sought after candidates in the Recruitment Market.

In this article, I will share some JavaScript tips, tips, and best practices. They are applicable to both the browser's JavaScript engine and the server-side JavaScript interpreter.

The sample code in this article passes the test on the latest version of Google Chrome 30 (V8 3.20.17.15.

1. When assigning values to variables for the first time, you must use the var keyword.

Variables are directly assigned without declaration. By default, they are used as a new global variable. Avoid using global variables whenever possible.

2. Use = replace =

= And! = The operator will automatically convert the data type as needed. But = and! = No, they compare values and data types at the same time, which also makes them equal to = and! = Fast.

The 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. The logical results of underfined, null, 0, false, NaN, and null strings are all false.
4. Use a semicolon at the end of the line

In practice, it is best to use a semicolon. If you forget to write it, The JavaScript interpreter will be automatically added in most cases. For more information about the use of semicolons, see the truth about semicolons in JavaScript.

5. Use the object constructor

The 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 contructor with caution.
Typeof: JavaScript unary operator, used to return the original type of the variable in the form of a string. Note that typeof null also returns the object. Most object types (Array, time Date, etc) will also return the object
Contructor: Internal prototype attribute, which can be rewritten through code
Instanceof: JavaScript operator, which is searched by the constructor in the prototype chain. If it is found, true is returned. Otherwise, false is returned.

The Code is as follows:


Var arr = ["a", "B", "c"];
Typeof arr; // return "object"
Arr instanceof Array // true
Arr. constructor (); // []


7. Use self-called Functions
A Function is automatically executed after it is created. It is generally called a Self-Invoked Anonymous Function or an Immediately Invoked Function Expression ). The format is as follows:

The Code is as follows:


(Function (){
// The Code placed here will be automatically executed
})();
(Function (a, B ){
Var result = a + B;
Return result;
}) (10, 20)

8. Randomly retrieve members from the array

The 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)];


9. Obtain random numbers within a specified range
This function is especially useful when generating false data for testing, such as the number of salaries within a specified range.

The Code is as follows:


Var x = Math. floor (Math. random () * (max-min + 1) + min;


10. Generate a number array from 0 to the specified value

The Code is as follows:


Var numbersArray = [], max = 100;
For (var I = 1; numbersArray. push (I ++) <max;); // numbers = [1, 2, 3... 100]


11. generate random letters and numbers

The 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 the order of number Arrays

The 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 numbers array will be similar to [120, 5,228,-215,400,458,-85411,122] */


Here we use the array sorting function built in JavaScript. A better way is to use special code (such as the Fisher-Yates algorithm). For details, see the discussion on StackOverFlow.

13. Remove spaces from strings

Java, C #, PHP, and other languages all implement special String space-removing functions, but JavaScript does not. You can use the following code to function a trim function for the String object:

The Code is as follows:


String. prototype. trim = function () {return this. replace (/^ \ s + | \ s + $/g ,"");};


The new JavaScript Engine already has the native Implementation of trim.

14. appending between Arrays

The Code is as follows:


Var array1 = [12, "foo", {name "Joe"},-2458];
Var array2 = ["Doe", 555,100];
Array. prototype. push. apply (array1, array2 );
/* The array1 value is [12, "foo", {name "Joe"},-2458, "Doe", 555,100] */


15. convert an object to an array

The Code is as follows:


Var argArray = Array. prototype. slice. call (arguments );


16. Verify if it is a number

The Code is as follows:


Function isNumber (n ){
Return! IsNaN (parseFloat (n) & isFinite (n );
}


17. Verify whether it is an array

The Code is as follows:


Function isArray (obj ){
Return Object. prototype. toString. call (obj) = '[object Array]';
}


However, if the toString () method is overwritten, it will not work. You can also use the following method:

The Code is as follows:


Array. isArray (obj); // its a new Array method


If frame is not used in the browser, you can also use instanceof. However, if the context is too complex, errors may occur.

The 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]
// The constructor of myArray has been lost, and the instanceof result will be abnormal
// The constructor cannot be shared across frames.
Arr instanceof Array; // false


18. obtain the maximum and minimum values in the array.

The 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 );


19. Clear the Array

The Code is as follows:


Var myArray = [12,222,100 0];
MyArray. length = 0; // myArray will be equal to [].


20. Do not directly delete or remove elements from the array.
If you directly use delete For array elements, the elements are not deleted, but are set to undefined. Splice should be used to delete array elements.

Avoid:

The 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
/* The items result is [12,548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,119] */

But should:

The 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
/* The items result is [12,548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,119].


Delete can be used to delete attributes of an object.

21. Use the length attribute to truncate the array.

In the preceding example, The length attribute is used to clear the array. It can also be used to truncate the array:

The Code is as follows:


Var myArray = [12,222,100 0, 124, 98, 10];
MyArray. length = 4; // myArray will be equal to [12,222,100 0, 124].


At the same time, if you increase the length attribute, the length value of the array will increase, and undefined will be used to fill the new element. Length is a writable attribute.

The Code is as follows:


MyArray. length = 10; // the new array length is 10
MyArray [myArray. length-1]; // undefined

22. Use logic in conditions and

The Code is as follows:


Var foo = 10;
Foo = 10 & doSomething (); // is the same thing as if (foo = 10) doSomething ();
Foo = 5 | doSomething (); // is the same thing as if (foo! = 5) doSomething ();


Logical or can also be used to set default values, such as the default values of function parameters.

The Code is as follows:


Function doSomething (arg1 ){
Arg1 = arg1 | 10; // arg1 will have 10 as a default value if it's not already set
}


23. Make the map () function method cycle the data.

The Code is as follows:


Var squares = [1, 2, 4]. map (function (val ){
Return val * val;
});
// Squares will be equal to [1, 4, 9, 16]


24. Retain the specified decimal places

The Code is as follows:


Var num = 2.443242342;
Num = num. toFixed (4); // num will be equal to 2.4432


Note that toFixec () returns a string, not a number.

25. Floating Point computing problems

The 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? Because 0.1 + 0.2 equals 0.30000000000000004. JavaScript numbers follow the IEEE 754 standard and are represented by 64-bit floating point decimals. For details, see how the numbers in JavaScript are encoded.

You can solve this problem by using toFixed () and toPrecision.

26. Check the object attributes through the for-in Loop
The following usage prevents objects from entering the prototype attribute during iteration.

The Code is as follows:


For (var name in object ){
If (object. hasOwnProperty (name )){
// Do something with name
}
}


27. Comma Operator

The 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. temporary storage of variables for calculation and query
In the jQuery selector, You can temporarily store the entire DOM element.

The 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. Check the input isFinite () parameters in advance

The Code is as follows:


IsFinite (0/0); // false
IsFinite ("foo"); // false
IsFinite ("10"); // true
IsFinite (10); // true
IsFinite (undefined); // false
IsFinite (); // false
IsFinite (null); // true, which deserves special attention.


30. Avoid using negative numbers in the array for indexing.

The 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]


Note that the index parameter passed to splice should not be a negative number. When it is a negative number, the elements will be deleted from the end of the array.

31. Use JSON for serialization and deserialization

The Code is as follows:


Var person = {name: 'saad', age: 26, department: {ID: 15, name: "R & D "}};
Var stringFromPerson = JSON. stringify (person );
/* StringFromPerson returns "{" name ":" Saad "," age ": 26," department ": {" ID ": 15," name ": "R & D "}}"*/
Var personFromString = JSON. parse (stringFromPerson );
/* The value of personFromString is the same as that of the person object */


32. Do not use eval () or function Constructor
Eval () and Function consturctor have high overhead. Each call, the JavaScript engine must convert the source code into executable code.

The Code is as follows:


Var func1 = new Function (functionCode );
Var func2 = eval (functionCode );


33. Avoid using ()
With () can be used to add variables to the global scope. Therefore, if there are other variables with the same name, it is easy to confuse and the second value will be overwritten.

34. Do not use for-in for Arrays
Avoid:

The Code is as follows:


Var sum = 0;
For (var I in arrayNumbers ){
Sum + = arrayNumbers [I];
}


But:

The Code is as follows:


Var sum = 0;
For (var I = 0, len = arrayNumbers. length; I <len; I ++ ){
Sum + = arrayNumbers [I];
}


Another benefit is that the I and len variables are initialized only once in the first declaration of the for loop, which is faster than the following statement:

The Code is as follows:


For (var I = 0; I <arrayNumbers. length; I ++)


35. Use a function instead of a string when it is passed to setInterval () and setTimeout ()
If it is passed to a string of setTimeout () and setInterval (), they will convert it in a way similar to eval, which must be slower, so do not use:

The Code is as follows:


SetInterval ('dosomethingperiodically () ', 1000 );
SetTimeout ('dosomethingafterfiveseconds () ', 5000 );


Instead, use:

The Code is as follows:


SetInterval (maid, 1000 );
SetTimeout (doSomethingAfterFiveSeconds, 5000 );

36. Use switch/case to replace a large stack of if/else

When judging that there are more than two branches, it is faster to use switch/case, and it is more elegant and more conducive to the Code Organization. Of course, if there are more than 10 branches, do not use switch/case.

37. use numeric intervals in switch/case

In fact, the case condition in switch/case can also be written as follows:

The 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); // "Baby" is returned"


38. Use an object as the prototype of the object

In this way, you can specify an object as a parameter to create a new object based on this prototype:

The Code is as follows:


Function clone (object ){
Function OneShotConstructor (){};
OneShotConstructor. prototype = object;
Return new OneShotConstructor ();
}
Clone (Array). prototype; // []


39. HTML field conversion functions

The Code is as follows:


Function escapeHTML (text ){
Var replacements = {"<": "<", ">": "> ","&":"&","\"":"""};
Return text. replace (/[<> & "]/g, function (character ){
Return replacements [character];
});
}


40. Do not use try-catch-finally inside the loop

The catch part in try-catch-finally assigns an exception to a variable during execution, which is constructed into a new variable in the runtime scope.

Avoid:

The Code is as follows:


Var object = ['foo', 'bar'], I;
For (I = 0, len = object. length; I Try {
// Do something that throws an exception
}
Catch (e ){
// Handle exception
}
}


However, we should:

The Code is as follows:


Var object = ['foo', 'bar'], I;
Try {
For (I = 0, len = object. length; I // Do something that throws an exception
}
}
Catch (e ){
// Handle exception
}

41. set timeout when using XMLHttpRequests
When XMLHttpRequests is executed, when there is no response for a long time (such as a network problem), the connection should be aborted. You can use setTimeout () to do this:

The 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 ();


At the same time, you must note that do not initiate multiple XMLHttpRequests requests at the same time.

42. Processing WebSocket timeout

Generally, after a WebSocket connection is created, if there is no activity within 30 seconds, the server will process the connection timeout, And the firewall can also process the timeout for connections that are not active in a unit cycle.

To prevent this situation, you can send an empty message to the server at intervals. The following two functions can be used to achieve this requirement. One is used to maintain the active state of the connection, and the other is used to end the State.

The Code is as follows:


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 () function can be placed at the end of the onOpen () method connected to WebSocket, and cancelKeepAlive () is placed at the end of the onClose () method.

43. Time note: the original operator is faster than the function call, And VanillaJS is used.
For example, do not:

The Code is as follows:


Var min = Math. min (a, B );
A. push (v );


This can be replaced:

The Code is as follows:


Var min = a <B? A: B;
A [A. length] = v;


44. Pay attention to the code structure during development. Check and compress JavaScript code before going online.
You can use tools such as JSLint or JSMin to check and compress the 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.