20 practical JavaScript tips to share
- 2020-03-30 04:25:08
- OfStack
As we all know, JavaScript is a very popular programming language that allows developers to develop not only fancy Web applications, but also mobile applications (such as PhoneGap or Appcelerator), as well as server-side implementations such as NodeJS, Wakanda, and others. In addition, many developers will choose JavaScript as a starter language and use it for little things like pop-ups.
In this article, the authors will share tips, best practices, and other useful tips for JavaScript development that will definitely benefit you, whether you're a front-end developer or a server-side developer.
The code snippets provided in this article have been tested with the latest version of Chrome 30, which USES the V8 JavaScript engine (V8 3.20.17.15).
1. Don't forget the var keyword the first time you assign a variable
Assign a value to an undeclared variable, which is automatically created as a global variable. Global variables should be avoided in JS development.
2. Replace == with ==
And never use = or! =.
[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 semicolons as line termination characters
It's a good practice to use semicolons where lines end, and even if the developer forgets to add a semicolon, the compiler won't notice because, in most cases, the JavaScript parser will do it automatically.
4. Create a constructor
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");
5. Typeof, instanceof, and constructor should be used with care
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-calling anonymous function or an immediate calling function expression (LLFE). Functions are executed automatically when they are created, like this:
(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
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
Get a random number in a specific range
The following code is very general, when you need to generate a false data to test, such as a random value before the minimum wage and the maximum.
var x = Math.floor(Math.random() * (max - min + 1)) + min;
Generate a set of random Numbers between the number 0 and the maximum number
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
function generateRandomAlphaNum(len) {
var rdmstring = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}
Shuffle your array of Numbers
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});
12. String Tim function
The trim function deletes white space characters from a string and can be used in Java, C#, PHP, and many other languages.
String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};
13. Append the array
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
Converts the parameter object to an array
var argArray = Array.prototype.slice.call(arguments);
Verify that a given parameter is a number
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
Verify that a given parameter is an array
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
Note that if the toString() method is overwritten, you will not get the expected result.
Or you could write:
Array.isArray(obj); // its a new Array method
Similarly, if you use more than one frame, you can use instancesof, and if you have too much, the result will be the same.
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
Get maximum and minimum values from 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);
Empty the array
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].
Do not delete items from an array with delete
Developers can use split instead of delete to delete array items. Instead of deleting an undefined item in an array, use delete instead.
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
Can also...
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 delete method should delete an object property.
20. Shorten the array with the length property
Developers can also use the length property to shorten the array, as mentioned above.
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
If the length of the array 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.
myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined