As you know, JavaScript is the number one programming language in the world. It is the language of the Web, the language of mobile hybrid apps (such as PhoneGap or Appcelerator), and the server-side language (such as NodeJS or Wakanda), and has many other implementations. At the same time, it is also the enlightenment language for many novices, because 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 organized, standardized and performantly efficient code have become sought after in the talent market.
It should be noted that the code snippets in this article were tested on the latest Google Chrome (version number 30), which uses the V8 JavaScript engine (V8 3.20.17.15).
1 – Don’t forget to use the var keyword when assigning a value to a variable for the first time
Assigning a value to an undefined variable will result in the creation of a global variable. Avoid global variables.
2 – Use === instead of ==
== (or !=) operator will automatically perform type conversion when needed. The === (or !==) operation does not perform any conversion. It compares values and types, and is also considered faster than ==.
[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
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; };
//Not initialized in the constructor Attributes
var occupation;
this.getOccupation = function() { return occupation; };
this.setOccupation = function(newOcc) { occupation =
newOcc; };
}
4 – Use semicolons at the end of statements Using semicolons at the end of statements is a good practice. You won't be warned if you forget to write it, because in most cases the JavaScript interpreter will add the semicolon for you.
5 – Create the constructor of the object
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");
6 – Use typeof, instanceof and constructor carefully
var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); / /[]
7 – Create a Self-calling Function This is often called a Self-Invoked Anonymous Function or immediate call Function expression (IIFE-Immediately Invoked Function Expression). This is a function that is automatically executed immediately after creation, usually 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 item from the array var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor( Math.random() * items.length)];[code]
9 – Get a random number in a specific range
This code snippet is very useful when you want to generate test data Useful, such as a random salary value between the minimum and maximum values.
[code]var x = Math.floor(Math.random() * (max - min 1)) min;
10 – generated between 0 and the set maximum value An array of numbers
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(36).substr(2));
return rdmString.substr(0, len);
}
12 – scramble an array of numbersvar numbers = [5, 458, 120, -215, 228, 400, 122205, -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, 122205] */
13 – String’s trim function
There is a classic trim function in Java, C#, PHP and many other languages, which is used to remove spaces in strings. There is no such function in JavaScript, so we need to add this function to the String object.
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 Go to another array
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 implement two arrays connection, but its return value is a new array. Here is the direct change to array1
15 – Convert the arguments object into an array
var argArray = Array.prototype.slice.call(arguments);
arguments object is an array-like object, but not a real array
16 – Verify whether the argument is a number (number)function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
17 – Verify whether the parameter is an arrayfunction isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array ]' ;
}
Note: If the toString() method is overridden, you will not be able to get the desired results using this technique. Or you can use:
Array.isArray(obj); // This is a new array method
If you are not using multiple frames, you can also use the instanceof method. But if you have multiple contexts, you'll get wrong results.
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 – Get the maximum or minimum value in an array of numbers var numbers = [5, 458, 120, -215, 228, 400, 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
//Translator’s Note: The technique of passing parameters using the Function.prototype.apply method is used here
19 – Clear an array var myArray = [12, 222, 1000];
myArray.length = 0; // myArray will be equal to [].
20 – Do not use delete to remove items from an array.
Use splice instead of delete to delete an item from an array. Using delete only replaces the original item with undefined, but does not actually delete it from the array.
Don’t use this method:
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:
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] */
delete method should be used to delete an attribute of an object.
21 – Use length to truncate an array
Similar to the way to clear the array above, we use the length property to truncate an array.
var myArray = [12, 222, 1000, 124, 98, 10 ];
myArray.length = 4; // myArray will be equal to [12, 222, 1000, 124].
Also, if you set the length of an array to a larger one than it is now value, then the length of the array will be changed, and new undefined items will be added. The length of an array is not a read-only property.
myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined
22 – Use logical AND/OR to make conditional judgments
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
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 over the items in an array
var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]
24 – Round a number to N decimal places var num =2.443242342;
num = num.toFixed(4); / / num will be equal to 2.4432
25 – Floating point problem0.1 0.2 === 0.3 // is false
9007199254740992 1 // is equal to 9007199254740992
9007199254740992 2 // is equal to 9007199254740994
Why is this happening? ? 0.1 0.2 is equal to 0.30000000000000004. You need to know that all JavaScript numbers are internally represented as floating point numbers in 64-bit binary, complying with the IEEE 754 standard. For more introduction, you can read this blog post. You can solve this problem using toFixed() and toPrecision() methods.
26 – When using for-in to traverse the internal properties of an object, pay attention to checking the properties
The following code snippet can avoid accessing prototype properties when traversing an object's properties
for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}
27 – Comma operator
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 that require calculation or querying
For jQuery selectors, we 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 – Validate parameters before calling isFinite() isFinite(0/0); // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undifined); // false
isFinite(); // false
isFinite(null); // true !!!
30 – avoid in arrays Negative indexes
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 the argument when calling indexOf is not negative.
31 – JSON-based serialization and deserialization
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 constructor
Using eval and Function constructors are very expensive operations because each time they call the script engine to convert the source code into executable code.
var func1 = new Function(functionCode);
var func2 = eval(functionCode);
33 – Avoid using with()
Using with() will insert a global variable. Therefore, variables with the same name will have their values overwritten and cause unnecessary trouble.
34 – Avoid using for-in to iterate over an array
Avoid using this:
var sum = 0;
for (var i in arrayNumbers) {
sum = arrayNumbers[i];
}
A better way is:
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i ) {
sum = arrayNumbers[i];
}
The additional benefit is that i and len are both The value of the variable is only executed once, which is more efficient than the following method:
for (var i = 0; i < arrayNumbers.length; i )
Why? Because arrayNumbers.length will be calculated every time it loops.
35 – Pass functions instead of strings when calling setTimeout() and setInterval(). If you pass a string to setTimeout() or setInterval(), the string will be parsed as if using eval, which is very time-consuming.
Don’t use:
setInterval('doSomethingPeriodically() ', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000)
And use:
setInterval(doSomethingPeriodically, 1000);
setTimeOut(doSomethingAfterFiveSeconds, 5000);
36 – Use switch/case statement, and Instead of a long list of if/else, when judging more than 2 situations, using switch/case is more efficient and more elegant (easier to organize code). But don’t use switch/case when there are more than 10 situations to be judged.
37 – Use switch/case when judging the numerical range
In the following situation, it is reasonable to use switch/case to judge the numerical range:
function getCategory(age) {
var category = "";
switch (true) {
case isNaN(age):
category = "not an age";
break; category = "Baby" ;
break;
default:
category = "Young";
break;
};
return category;
}
getCategory(5) ; // will return "Baby"
//Generally, for judging the numerical range, it is more appropriate to use if/else. switch/case is more suitable for judging certain values
38 – Specify the prototype object for the created object
It is possible to write a function to create an object with specified parameters as prototype :
Copy code
}
clone(Array).prototype; // []
39 – one HTML escape function
Copy code
at runtime, each time the catch clause is executed, the caught exception object will be assigned to a variable, and in the try-catch-finally structure, each time This variable will be created
.
Avoid writing like this:
Copy code
The code is as follows:
var object = ['foo' , 'bar'], i;
for (i = 0, len = object.length; i
and use:
Copy code
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 for XMLHttpRequests.
After an XHR request takes a long time (for example, due to network problems), you may need to abort the request, then you can use setTimeout() with the XHR call.
Copy code
The code is as follows:
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {}, 60*1000 /* timeout after a minute */ );xhr.open('GET', url, true);
xhr.send();
Also, generally you should avoid synchronous Ajax requests entirely.
42 - Handling WebSocket timeouts
Normally, after a WebSocket connection is created, the server will time out your connection after 30 seconds if you have no activity. Firewalls also disconnect after a period of inactivity.
To prevent timeout issues, you may need to intermittently send empty messages to the server. To do this, you can add the following two functions to your code: one to maintain the connection and one to cancel the connection hold. With this technique, you can control the timeout issue.
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);
}
}
keepAlive() The 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);
and use:
var min = a < b ? a b;
A[A.length] = v;
44 – when encoding Don’t forget to use code tidying tools . Use JSLint and code compression tools (minification) (such as JSMin) before going online. "Time Saving Tool: Code Beautification and Formatting Tool"
45 – JavaScript is incredible.
Summary
I know there are many other tips, tricks, and best practices out there, so if you have anything else you’d like to add or have feedback or corrections to the ones I’ve shared, please say so in the comments.