45 practical tips that JavaScript programmers should know

Source: Internet
Author: User
Tags array length arrays constructor eval json min tostring trim
As you know, JavaScript is the world's number one programming language. 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 there are 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 have mastered JavaScript and can write organization-specific and performance-efficient code have become hunting targets in the talent market.
It should be noted 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).

1-Don't forget to use the var keyword when first assigning 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 ==
The == (or! =) Operator automatically performs type conversion when needed. === (or! ==) operation does not perform any conversion. It compares values and types, and is also considered to be better than == in speed.

Copy the code code 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-Implement private variables using closures
Copy the code code as follows:

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 constructor
    var occupation;
    this.getOccupation = function () {return occupation;};
    this.setOccupation = function (newOcc) {occupation =
                         newOcc;};
}

4-Use a semicolon at the end of the statement
It is good practice to use semicolons at the end of a statement. You won't be warned if you forget to write, because in most cases the JavaScript interpreter will help you with semicolons.
5-Constructor for creating objects
Copy the code code as follows:
function Person (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

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

6-Be careful with typeof, instanceof, and constructor
Copy the code code as follows:
var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor (); // []

7-Create a Self-calling Funtion
This is often called Self-Invoked Anonymous Function or IIFE-Immediately Invoked Function Expression. This is a function that executes automatically as soon as it is created, usually as follows:
Copy the code code 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 an array
Copy the code code as follows:
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, such as a random salary value between the minimum and maximum values.
[code] var x = Math.floor (Math.random () * (max-min + 1)) + min;

10-Generate an array of numbers between 0 and the set maximum
Copy the code code as follows:
var numbersArray = [], max = 100;

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

11-Generate a random alphanumeric string
Copy the code code as follows:
function generateRandomAlphaNum (len) {
    var rdmstring = "";
    for (; rdmString.length <len; rdmString + = Math.random (). toString (36) .substr (2));
    return rdmString.substr (0, len);
}

12-Shuffle an array of numbers
Copy the code code 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] * /

13-String's trim function
In Java, C #, PHP, and many other languages, there is a classic trim function that removes space characters from strings, but not in JavaScript, so we need to add this function to String objects.
Copy the code code as follows:

String.prototype.trim = function () {return this.replace (/ ^ \ s + | \ s + $ / g, "");}; // Remove the leading and trailing spaces of the string, excluding the spaces inside the string

14-Append one array to another
Copy the code code 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] * /
// In fact, concat can directly connect two arrays, but its return value is a new array. Here is directly change array1
15-Converting arguments objects into an array

Copy the code code as follows:
var argArray = Array.prototype.slice.call (arguments);
The arguments object is an array-like object, but not a real array

16-Verify that the parameter is a number
Copy the code code as follows:
function isNumber (n) {
    return! isNaN (parseFloat (n)) && isFinite (n);
}

17-Verify that the parameter is an array
Copy the code code as follows:
function isArray (obj) {
    return Object.prototype.toString.call (obj) === '[object Array]';
}

Note: If the toString () method is overridden, you will not get the desired result using this technique. Or you can use:
Copy the code code as follows:

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 will get wrong results.
Copy the code code 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]

// 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
Copy the code code 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);
// Translator's Note: The technique of passing parameters by Function.prototype.apply method is used here

19 – Empty an array
Copy the code code as follows:
var myArray = [12, 222, 1000];
myArray.length = 0; // myArray will be equal to [].

20-Do not use delete to delete items in an array.
Use splice instead of delete to delete an item from an array. Using delete just replaces the original item with undefined, not actually deleting from the array.

Don't use this way:

Copy the code code 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, un
defined × 1, "Doe", 2154, 119] * /

While using:
Copy the code code 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 be used to delete an attribute of an object.
21-Use length to truncate an array
Similar to the way of emptying the array above, we use the length property to truncate an array.

Copy the code code as follows:
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 the current one, the length of the array will be changed, and new undefined items will be added to make up. The length of the array is not a read-only property.
Copy the code code as follows:
myArray.length = 10; // the new array length is 10
myArray [myArray.length-1]; // undefined

22-Conditional judgment using logical AND / OR
Copy the code code as follows:

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
Copy the code code as follows:

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 through the items in an array
Copy the code code as follows:
var squares = [1,2,3,4] .map (function (val) {
    return val * val;
});
// squares will be equal to [1, 4, 9, 16]

24 – round one digit, leaving N decimal places
Copy the code code as follows:
var num = 2.443242342;
num = num.toFixed (4); // num will be equal to 2.4432

25 – Floating-point numbers
Copy the code code as follows:
0.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 equals 0.30000000000000004. You need to know that all JavaScript numbers are internally floating-point numbers in 64-bit binary, in accordance with the IEEE 754 standard. For more introduction, you can read this blog post. You can use the toFixed () and toPrecision () methods to solve this problem.
26 – Use for-in to check the properties of an object
The following code snippet can avoid accessing the properties of the prototype when traversing an object property

Copy the code code as follows:

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

27 – comma operator
Copy the code code 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-Caching Variables That Need Calculation or Querying
For jQuery selectors, we better cache these DOM elements.

Copy the code code as follows:
var navright = document.querySelector ('# right');
var navleft = document.querySelector ('# left');
var navup = document.querySelector ('# up');
var navdown = document.querySelector ('# down');

29-Verify parameters before calling isFinite ()
Copy the code code as follows:
isFinite (0/0); // false
isFinite ("foo"); // false
isFinite ("10"); // true
isFinite (10); // true
isFinite (undifined); // false
isFinite (); // false
isFinite (null); // true !!!

30-Avoid negative indexes in arrays
Copy the code code 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]

Make sure that the argument to indexOf is not negative.
31 – JSON-based serialization and deserialization

Copy the code code as follows:
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 constructors
Using eval and Function constructors is a very expensive operation because every time they call the script engine to convert the source code into executable code.
Copy the code code as follows:
var func1 = new Function (functionCode);
var func2 = eval (functionCode);

33 – Avoid using with ()
Using with () inserts a global variable. Therefore, the variable with the same name will be overwritten and cause unnecessary trouble.
34 – Avoid using for-in to iterate over an array
Avoid using this approach:
Copy the code code as follows:
var sum = 0;
for (var i in arrayNumbers) {
    sum + = arrayNumbers [i];
}

A better way is:
Copy the code code as follows:
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i <len; i ++) {
    sum + = arrayNumbers [i];
}

An added benefit is that the values of the i and len variables are only executed once, which is more efficient than
Copy the code code as follows:
for (var i = 0; i <arrayNumbers.length; i ++)

why? Because arrayNumbers.length is 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.
Do not use:
Copy the code code as follows:

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

And use:
Copy the code code as follows:

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

36 – Use switch / case statements instead of a long list of if / else
When judging more than two cases, using switch / case is more efficient and more elegant (easier to organize the code). But don't use switch / case when you judge more than 10 cases.
37 – Use switch / case when judging a range of values
In the following cases, it is reasonable to use switch / case to determine the range of values:
Copy the code code 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); // will return "Baby"
// Generally, for judgment of numerical range, if / else would be more appropriate. Switch / case is more suitable for judging a certain value

38-Specify a prototype object for the created object
It is possible to write a function to create an object with the specified parameters as a prototype:
Copy the code code as follows:
function clone (object) {
    function OneShotConstructor () {};
    OneShotConstructor.prototype = object;
    return new OneShotConstructor ();
}
clone (Array) .prototype; // []

39-An HTML Escape Function
Copy the code code as follows:
function escapeHTML (text) {
    var replacements = {"<": "<",
">": ">", "&": "&", "\" ":" ""};
    return text.replace (/ [<> & "] / g, function (character) {
        return replacements [character];
    });
}

40 – Avoid using try-catch-finally inside loops
At run time, each time the catch clause is executed, the caught exception object is assigned a variable, and in the try-catch-finally structure, this variable is created each time.
Avoid this:

Copy the code code as follows:
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
    }
}

While using:
Copy the code code as follows:
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-Set timeout for XMLHttpRequests.
After an XHR request takes a long time (for example due to a network problem), you may need to abort the request, then you can use setTimeout () on XHR calls.
Copy the code code 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 ();

Also, in general you should completely avoid synchronous Ajax requests.
42-Handle WebSocket timeout
Normally, after a WebSocket connection is created, the server will time out your connection after 30 seconds if you are not active. The firewall also disconnects after a period of inactivity.
To prevent timeouts, you may need to send empty messages to the server intermittently. To do this, you can add the following two functions to your code: one to keep the connection and the other to cancel the connection. With this technique, you can control the issue of timeouts.

Use a timerID:

Copy the code code 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 () method should be added at the end of the onOpen () method of the webSOcket connection, and cancelKeepAlive () 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, don't use:
Copy the code code as follows:
var min = Math.min (a, b);
A.push (v);

And use:
Copy the code code as follows:
var min = a <b? a b;
A [A.length] = v;

44-Don't forget to use code cleanup tools when coding. Use JSLint and code minification tools (such as JSMin) before going live. "Time-saving tool: code beautification and formatting tool"
45-JavaScript is incredible.

to sum up

I know there are many other tips, tricks, and best practices, so if you have other feedback or corrections that you want to add or share with me, please point out in the comments.

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.