How to Write efficient and concise JavaScript code

Source: Internet
Author: User

Simplified code

Using a shorter statement can not only reduce the number of characters entered, but also reduce the file size. The execution efficiency of most code that adopts simple writing is slightly improved.

1. simplified definition of common objects

Use var obj ={}; instead of var obj = new Object ();

Use var arr = []; instead of var arr = new Array ();

2. Streamline the if statement

The ternary operator can effectively streamline the if statement that only involves the value transfer operation, for example:

Var score = 60, grade; if (score <60) {grade = "fail";} else {grade = "pass ";}

It can be simplified:

Var score = 60; var grade = score <60? "Fail": "pass ";

The ternary operators also support nesting, but too many layers of nesting will affect the readability of the program, which requires more consideration.

3. Use JSON

JSON is a lightweight data format. Its lightweight structure definition is very simple.

var obj = {};obj.p1 = 'a';obj.p2 = 'b';obj.p3 = 'c';

It can be simplified:

var obj = {    p1 : 'a',    p2 : 'b',    p3 : 'c',};
Use efficient code

There are a lot of efficiency optimization articles circulating on the Internet, and some professional Javascript books have also talked about a lot. Therefore, we will only list some of the articles that are rarely mentioned here.

1. Streamline the cycle body

The efficiency of a loop is largely determined by the loop body. The difference between for and while is too small. Consider the following code. Its function is to add events to a batch of elements:

function addEvent(elems, eventName, handler) {    for (var i = 0, len = elems.length; i < len; i++) {        if (window.attachEvent) {            elems[i].attachEvent(”on” + eventName, handler);        } else if (window.addEventListener) {            elems[i].addEventListener(eventName, handler, false);        }    }}

Every execution of the Loop will judge whether the attachEvent or addEventListener of the window object exists. In fact, this is enough to judge once. In addition, the String concatenation of "on + eventName" will be executed repeatedly. The optimization is as follows:

function addEvent(elems, eventName, handler) {    var i = -1, len = elems.length;    if (window.attachEvent) {        eventName = “on” + eventName;        while (++i < len) {            elems[i].attachEvent(eventName, handler);        }    } else if (window.addEventListener) {        while (++i < len) {            elems[i].addEventListener(eventName, handler, false);        }    }}

2. Try to use native functions instead of custom functions

When you perform an operation on a Javascript built-in type variable, you should first check whether this operation has a native method.

What do you do to generate a copy of an array? Traversing array elements and assigning values to another array one by one seems to be the only method. In fact, native Array. prototype. slice can achieve the purpose of replication. This method returns selected elements from an array without affecting the original array. If the parameter is left blank, all elements are returned.

Array. prototype. slice can also operate on some types that are not arrays but can be accessed through digital indexes, such as arguments:

function test() {    alert(Array.prototype.slice.call(arguments));}test(1, 2, 3); // output “1,2,3″

In Firefox, it can even operate HtmlCollection. Unfortunately, it cannot be done in IE.

Another example is Array sorting. In general, we do not need to write another sorting algorithm. It is enough to use native Array. prototype. sort. The sort method has only one parameter. this parameter is a function that determines who is in the first place of the two elements. By default, the two elements are sorted in character order. For example, 11 is ranked before 2. To sort by number, you can write as follows:

var arr = [11, 2, 0, 12, 33];arr.sort(    function(a, b) {        return a - b;    });

You can also sort by an object attribute:

var arr = [    { id : 11 },    { id : 0 },    { id : 22 }];arr.sort(    function(a, b) {        return a.id - b.id;    });

3. array deduplication

The Array type does not provide the deduplication method. If you want to remove the repeated elements of the Array, you have to find a solution:

function unique(arr) {    var result = [], isRepeated;    for (var i = 0, len = arr.length; i < len; i++) {        isRepeated = false;        for (var j = 0, len = result.length; j < len; j++) {            if (arr[i] == result[j]) {                   isRepeated = true;                break;            }        }        if (!isRepeated) {            result.push(arr[i]);        }    }    return result;}

The general idea is to move the array elements one by one to another. During the handling process, check whether there are duplicates of the elements. If so, the elements are discarded directly. From nested loops, we can see that this method is very inefficient. We can use a hashtable structure to record existing elements, so as to avoid inner loops. Exactly, implementing hashtable in Javascript is extremely simple, and the improvements are as follows:

function unique(arr) {    var result = [], hash = {};    for (var i = 0, elem; (elem = arr[i]) != null; i++) {        if (!hash[elem]) {            result.push(elem);            hash[elem] = true;        }    }    return result;}
Make the code easier to read and maintain

Whether in development or after development, you can modify the code faster and more accurately by keeping the code clear and easy to read.

1. Connect HTML strings

I believe all of my friends who are working on front-end development have suffered from this torment: when connecting HTML, they are overwhelmed by hateful single quotes and double quotes. For example:

element.innerHTML = '<a href="' + url + '" onclick="alert(" + msg + '');">' + text + '';

Here is a string Formatting Function:

String.format = function(str) {    var args = arguments, re = new RegExp(”%([1-" + args.length + "])”, “g”);    return String(str).replace(        re,        function($1, $2) {            return args[$2];        }    );};

The call method is simple:

element.innerHTML = String.format('<a href="%1" onclick="alert('%2');">%3</a>', url, msg, text);

Replace % n with the nth parameter. This is much clearer.

2. Create a Config configuration object for your program

When writing a Java or C # program, we generally read the configuration information of the program from XML. In Javascript, it is not very cost-effective to use XML for configuration information. On the one hand, it is necessary to request an XML file or convert the XML string to an XML object. On the other hand, the XML Object method is complicated and lengthy. Lightweight JSON is the best choice.

Constants in the program should be placed in the Config configuration object, such as the Url of the Ajax request and the prompt of an operation. For example:

Var Config = {ajaxUrl: "test. jsp", successTips: "request completed "};

If the number of configurations is large, you can nest multiple layers based on the configuration type, for example:

Var Config = {url: {src1: "test1.jsp", src2: "test2.jsp ",..}, tips: {src1Suc: "request 1 completed", src2Suc: "request 2 completed ",..}};

Config should be placed at the beginning of the Program for easy viewing and modification.

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.