As we all know, JavaScript is a very popular programming language. Developers can use it to not only develop dazzling web programs, but also develop some mobile applications (such as PhoneGap or Appcelerator). It also has some server implementations, such as NodeJS, Wakanda and other implementations. In addition, many developers choose JavaScript as the introductory language and use it to make small things such as popups.
In this article, the author will share with you the small tips, best practices and other very practical content of JavaScript development. Whether you are a front-end developer or a server developer, you should take a look at these small tips, they will definitely benefit you.
The code snippets provided in the article have been tested in the latest version of Chrome 30, which uses the V8 JavaScript engine (V8 3.20.17.15).
1. When assigning a value to a variable for the first time, don't forget the var keyword
Assign a value to an undeclared variable, which will be automatically created as a global variable. In JS development, global variables should be avoided.
2. Use ===Replace ==
And never use = or! =.
The code copy 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 a semicolon as a line terminator
It is a good habit to use semicolons where line terminates, and even if the developer forgets to add semicolons, the compiler will not have any hints because in most cases, the JavaScript parser will automatically add them.
4. Create a constructor
The code copy is as follows:
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");
5. Be careful to use typeof, instanceof and constructor
The code copy is as follows:
var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); //[]
6. Create a Self-calling function
This is often referred to as a self-call anonymous function or an immediate call function expression (LLFE). When a function is created, it will be executed automatically, such as the following:
The code copy is as follows:
(function(){
// some private code that will be executed automatically
})();
(function(a,b){
var result = a+b;
return result;
})(10,20)
7. Create a random item for the array
The code copy is as follows:
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
8. Obtain a random number in a specific range
The following code is very common, when you need to generate a fake data for testing, such as getting a random value before the minimum wage and maximum.
The code copy is as follows:
var x = Math.floor(Math.random() * (max - min + 1)) + min;
9. Generate a set of random numbers between the number 0 and the maximum number
The code copy is as follows:
var numbersArray = [] , max = 100;
for( var i=1; numbersArray.push(i++) < max;); // numbers = [0,1,2,3 ... 100]
10. Generate a random set of alphanumeric characters
The code copy is as follows:
function generateRandomAlphaNum(len) {
var rdmstring = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}
11. Disrupt the array of numbers
The code copy is as follows:
var 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] */
12. String tim function
The trim function can delete whitespace characters in strings and can be used in multiple languages such as Java, C#, and PHP.
The code copy is as follows:
String.prototype.trim = function(){return this.replace(/^/s+|/s+$/g, "");};
13.Array append
The code copy is as follows:
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] */
14. Convert parameter objects to array
The code copy is as follows:
var argArray = Array.prototype.slice.call(arguments);
15. Verify whether a given parameter is a number
The code copy is as follows:
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
16. Verify that a given parameter is an array
The code copy is as follows:
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
Note that if the toString() method is rewritten, you will not get the expected result.
Or you can write this:
The code copy is as follows:
Array.isArray(obj); // its a new Array method
Similarly, if you use multiple frames, you can use instancesof, and if there is too much content, the result will also be errors.
The code copy 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]
// instance of will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array; // false
17. Get maximum and minimum values from array of numbers
The code copy is as follows:
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
18. Clear the array
The code copy is as follows:
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].
19.Don't use delete to delete items from array
Developers can use split instead of using delete to delete array items. Instead of deleting undefined items in the array, use delete instead.
The code copy 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] */
It's OK...
The code copy 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 delete an object property.
20. Use the length attribute to shorten the array
As mentioned above, developers can also use the length attribute to shorten the array.
The code copy is as follows:
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
If the array length value you define is too high, the length of the array will change and some undefined values will be filled into the array. The length property of the array is not read-only.
The code copy is as follows:
myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined