45 practical tips JavaScript programmers should know

  • 2020-03-30 02:13:40
  • OfStack

As you know, JavaScript is the number one programming language in the world, it's the language of the Web, it's the language of mobile hybrid apps (like PhoneGap or Appcelerator), it's a server-side language (like NodeJS or Wakanda), and it has many other implementations. It is also the language of enlightenment for many beginners, as it not only displays a simple alert message in the browser, but also can be used to control a robot (using nodebot, or nodruino). Developers who master JavaScript and can write well-organized, high-performance code have become the hunted in the talent market.
Note that the code snippets in this article were tested on the latest Google Chrome (version 30), which USES the V8 JavaScript engine (V8 3.20.17.15).

Don't forget to use the var keyword the first time you assign a value to a variable
Assigning a value to an undefined variable causes a global variable to be created. Avoid global variables.
2. Use === instead of ==
= = (or! The =) operator automatically performs type conversions when needed. = = = or! The ==) operation does not perform any conversion. It compares values and types, and is also considered superior to == in speed.


[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

Private variables are implemented using closures

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; };

    //Property 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 statements is a good practice. You won't be warned if you forget to write it, because most of the time the JavaScript interpreter will put a semicolon for you.
Create the constructor for the object
function Person(firstName, lastName){
    this.firstName =  firstName;
    this.lastName = lastName;
}

var Saad = new Person("Saad", "Mousliki");

Be careful with typeof, instanceof, and constructor
var arr = ["a", "b", "c"];
typeof arr;   // return "object"
arr  instanceof Array // true
arr.constructor();  //[]

7. Create a function self-calling Funtion.
This is often called the Anonymous Function called (Self - Invoked Anonymous Function) or instant call a Function Expression (IIFE - Immediately Invoked the 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- gets 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  �   Gets a random number in 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. 
[code]var x = Math.floor(Math.random() * (max - min + 1)) + min;

Generates an array of Numbers between 0 and the set maximum value
var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 ... 100]

Creates 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);
}

Shuffle an array of Numbers
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});

Trim function of the String
There is a classic trim function in Java, C#, PHP, and many other languages that removes whitespaces from strings, but not 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 preceding and trailing Spaces from the string, not the inner Spaces 

Add (append) an array to another array
var array1 = [12 , "foo" , {name: "Joe"} , -2458];

var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);

// Actually, concat You can join two arrays directly, but its return value is a new array. Here's the direct change array1

15.. Converts the arguments object to an array

var argArray = Array.prototype.slice.call(arguments);
arguments An object is a class array object, but not a real array 

16. Verify whether the parameter is a number (number)
function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

17.. Verifies that the parameters are arrays
function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

Note: if the toString() method is overridden, you cannot get the desired result using this trick. Or you can use:

Array.isArray(obj); //  This is a new one array The method of 

If you're not using multiple frames, you can also use the instanceof method. But if you have multiple contexts, you get the wrong result.
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

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: used here Function.prototype.apply Method to pass parameters 

Empty an array
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].

20. Do not use delete to delete an item in an array.

Use splice instead of delete to delete an item in the array. Using delete simply replaces the original item with undefined, not actually deleted from the array.

Don't use it:

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

To 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

The delete method should be used to delete a property of an object.
21. The length is used to truncate an array

Similar to the way we emptied the array above, we used 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].

In addition, if you set the length of an array to a value larger than it is now, 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(); //This is equivalent to if (foo == 10) doSomething();
foo == 5 || doSomething(); //  Is 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
}

The map() method is used 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]

Round a number to keep N decimal places
var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432

25 questions about floating point Numbers
0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

Why is that? 0.1+0.2 is equal to 0.30000000000000004. You should know that all JavaScript Numbers are internally expressed as 64-bit binary floating point Numbers, which are compliant with the IEEE 754 standard. For more information, read this blog post. You can use the methods toFixed() and toPrecision() to solve this problem.
26. When using for-in to iterate over the internal properties of an object, be careful to check the properties

The following code snippet avoids accessing the properties of the stereotype while traversing an object property


for (var name in object) {
    if (object.hasOwnProperty(name)) {
        // do something with name
    }
}

27 the 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. The cache needs to calculate or querying variables

For the jQuery selector, it's best to cache these DOM elements.

var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');

Verify the 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  !!!

The negative indexes in the array are to be avoided.
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 argument to indexOf is not negative.

31 serialization and deserialization of the contents based on JSON

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);

var personFromString = JSON.parse(stringFromPerson);

Avoid eval() and Function constructors
Using eval and Function constructors is expensive 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() inserts a global variable. Therefore, variables with the same name can be overwritten and cause unnecessary trouble.
34. Avoid using for-in to traverse an array
Avoid:
var sum = 0;
for (var i in arrayNumbers) {
    sum += arrayNumbers[i];
}

Better yet:
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
    sum += arrayNumbers[i];
}

An added benefit is that both I and len are evaluated only once, which is more efficient than the following:
for (var i = 0; i < arrayNumbers.length; i++)

Why is that? Because arraynumbers.length is calculated every time it loops.
The function is passed in when setTimeout() and setInterval() are called, not a string.
If you pass a string to setTimeout() or setInterval(), the string will be parsed as if it were eval, which can be very time consuming.
Do not use:

setInterval('doSomethingPeriodically()', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000)

With:

setInterval(doSomethingPeriodically, 1000);
setTimeOut(doSomethingAfterFiveSeconds, 5000);

The 36 wok USES the switch/case statement instead of a long string of if/else
Switch /case is more efficient and elegant (and easier to organize code) when judging situations greater than two. But don't use switch/case when there are more than 10 cases to judge.
37. Switch /case is used to determine the range of values
In the following case, 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;
        case (age >= 50):
            category = "Old";
            break;
        case (age <= 20):
            category = "Baby";
            break;
        default:
            category = "Young";
            break;
    };
    return category;
}
getCategory(5);  // will return "Baby"
// Generally speaking, for the judgment of numerical range, use  if/else  It would be appropriate.  switch/case  More suitable to determine the value of the judgment 

38. The dialog specifies the prototype object for the object created
It is possible to write a function to create an object with a specified parameter for prototype:
function clone(object) {
    function OneShotConstructor(){};
    OneShotConstructor.prototype= object;
    return new OneShotConstructor();
}
clone(Array).prototype ;  // []

39. An HTML escape function
function escapeHTML(text) {
    var replacements= {"<": "<", ">": ">","&": "&", """: """};
    return text.replace(/[<>&"]/g, function(character) {
        return replacements[character];
    });
}

Avoid using try-catch-finally inside the loop
At runtime, the caught exception object is assigned to a variable each time the catch clause is executed, and ina try-catch-finally structure, this variable is created each time.

Avoid writing:

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
    }
}

To use:
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 sets timeout for XMLHttpRequests.
If you need to abort an XHR request after it has taken a long time (for example, because of a network problem), you can use setTimeout() to accompany the XHR call.
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  );
xhr.open('GET', url, true);  

xhr.send();

In addition, you should generally avoid synchronous Ajax requests altogether.
42. The WMD handles WebSocket timeouts
Usually, after a WebSocket connection is created, the server will disconnect you after 30 seconds if you are not active. Firewalls also disconnect after a period of inactivity.

To prevent timeout issues, you may need to intermittently send empty messages to the server side. To do this, you can add the following two functions to your code: one to hold the connection and one to unhold the connection. With this technique, you can control timeouts.

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

The keepAlive() method should be added at the end of the webSOcket connection's onOpen() method, and the cancelKeepAlive() method at the end of the onClose() method.
Keep in mind that raw operators are always more efficient than function calls. Use VanillaJS.
For example, do not use:
var min = Math.min(a,b);
A.push(v);

With:
var min = a < b ? a b;
A[A.length] = v;

Don't forget to use the clean code tool when coding . Use JSLint and code compression tools (minification) (such as JSMin) before going live. Time saver: code beautification and formatting tools

45 JavaScript is incredible.

conclusion

I know there are many other tips, tricks and best practices out there, so if you have any others you'd like to add or have feedback or corrections to share with me, please point them out in the comments.


Related articles: