45 ultra-practical javascript Best Practices

Source: Internet
Author: User
Tags case statement

 

 

 

1. When you specify a variable for the first time, do not forget to use var:
Specifies an undeclared variable. If var is not used, it is declared as a global variable to avoid global variables;

2. replace '=' with '= ':
= (Or! =) The operator automatically performs type conversion when needed. = (Or! =) No type conversion is performed. Comparison value and type, = faster than =;
   [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. undefined, null, 0, false, NaN, ''(empty string) are all false;
4. Use a semicolon at the end of each line;
5. Create an object constructor:
    function Person(firstName, lastName){        this.firstName =  firstName;        this.lastName = lastName;            }      var Saad = new Person(Saad, Mousliki);



6. Use typeof, instanceof, and constructor with caution:
    var arr = [a, b, c];    typeof arr;   // return object    arr  instanceof Array // true    arr.constructor();  //[]



7. Create a self-called Function: This is usually called an anonymous Function or an Immediately Invoked Function Expression ). It will be executed when you create it. The format is as follows:
    (function(){        // some private code that will be executed automatically    })();      (function(a,b){        var result = a+b;        return result;    })(10,20)



8. Randomly obtain an entry in the array:
    var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];    var  randomItem = items[Math.floor(Math.random() * items.length)];



9. Get a random number in the specified range: This code is useful when you try to generate some false data for testing:
    var x = Math.floor(Math.random() * (max - min + 1)) + min;



10. generate an array of numbers:
    var numbersArray = [] , max = 100;    for( var i=1; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 ... 100]



11. Generate a random combination of numbers and letters:
    function generateRandomAlphaNum(len) {        var rdmString = ;        for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));        return  rdmString.substr(0, len);    }

12. Shuffling the number array:
    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 trim function: Javascript does not have a function like Java, c #, and PHP to clear String spaces. Therefore, we can add it to the String object:
    String.prototype.trim = function(){return this.replace(/^s+|s+$/g, );}; 

14. append an array to another array:
    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] */



15. argments parameters in the array:
    var argArray = Array.prototype.slice.call(arguments);



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



17. Verify whether a parameter is an array:
    function isArray(obj){        return Object.prototype.toString.call(obj) === '[object Array]' ;    }    Note that if the toString() method is overridden, you will not get the expected result using this trick.    Or use…    Array.isArray(obj); // its a new Array method    You could also use instanceof if you are not working with multiple frames. However, if you have many contexts, you will get a 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



18. Obtain the Maximum/minimum values 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);



19. Clear the array:
    var myArray = [12 , 222 , 1000 ];      myArray.length = 0; // myArray will be equal to [].



20. Do not use delete to remove items in the array: use split instead of delete to delete items in the array. Using delete will replace the specified item with undefined instead of removing it from the array;

Do not use
    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]   */



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    /* items will be equal to [12, 548, a, 5478, foo, 8852, undefined × 1, Doe, 2154,       119]   */



The delete method should be used to delete the attributes of an object.

21. Use length to intercept the array:
    var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];      myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].        myArray.length = 10; // the new array length is 10    myArray[myArray.length - 1] ; // undefined



22. Use logical operators for conditional processing:
Var foo = 10; foo = 10 & doSomething (); // equivalent to if (foo = 10) doSomething (); foo = 5 | doSomething (); // equivalent to if (foo! = 5) doSomething (); logical operator | it can also be used to set the default value function doSomething (arg1) {arg1 = arg1 | 10; // arg1 will use 10 as the default value if it is not set}



23. Use the map () method to traverse the array:
    var squares = [1,2,3,4].map(function (val) {          return val * val;      });    // squares will be equal to [1, 4, 9, 16] 



24. retain a few decimal places:
    var num =2.443242342;    num = num.toFixed(4);  // num will be equal to 2.4432



25. Floating Point Problems:
    0.1 + 0.2 === 0.3 // is false    9007199254740992 + 1 // is equal to 9007199254740992      9007199254740992 + 2 // is equal to 9007199254740994

You can use toFixed () and toPrecision () to solve this problem;

26. When using the loop, check the object attributes:
    for (var name in object) {          if (object.hasOwnProperty(name)) {            // do something with name                            }      }    



27. 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. cache variables:
    var navright = document.querySelector('#right');    var navleft = document.querySelector('#left');    var navup = document.querySelector('#up');    var navdown = document.querySelector('#down');



29. Verify the parameters before passing in isFinite:
    isFinite(0/0) ; // false    isFinite(foo); // false    isFinite(10); // true    isFinite(10);   // true    isFinite(undifined);  // false    isFinite();   // false    isFinite(null);  // true  !!!   



30. Avoid negative index in the array:
    var numbersArray = [1,2,3,4,5];    var from = numbersArray.indexOf(foo) ;  // from is equal to -1    numbersArray.splice(from,2);    // will return [5]



31. (JSON) serialization and deserialization:
    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 () or Function constructor:
    var func1 = new function(functionCode);    var func2 = eval(functionCode);



33. Avoid using the with () method: If you use with () to insert a variable in the global region, it is easy to confuse and override a variable name that is the same as its name.

34. Avoid using for-in loop in the array:
Do not use: var sum = 0; for (var I in arrayNumbers) {sum + = arrayNumbers [I];} use var sum = 0; for (var I = 0, len = arrayNumbers. length; I <len; I ++) {sum + = arrayNumbers [I];} Because I and len are the first statements in the loop, they are executed once each time they are instantiated, this method is faster than the following: for (var I = 0; I <arrayNumbers. length; I ++) Why? Array length: arraynNumbers is re-calculated during each loop iteration,



35. Do not pass a string to the setTimeout () and setInterval () Methods: If the string is passed in these two methods, the string will be re-computed as eval, which slows down.

Do not use: setInterval ('dosomethingperiodically () ', 1000); setTimeOut ('timeout ()', 5000); Use: setInterval (doSomethingPeriodically, 1000); setTimeOut (timeout, 5000 );



36. Replace the long if/else statement with the switch/case statement:

37. In case of a value range, you can select switch/case:
    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



38. Create an object whose attributes are a given object:
    function clone(object) {          function OneShotConstructor(){};        OneShotConstructor.prototype= object;          return new OneShotConstructor();    }    clone(Array).prototype ;  // []



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



40. Avoid using try-catch-finally in a loop:

41. Set timeouts for XMLHttpRequests:
    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();



42. Processing WebSocket Timeout:
    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);          }      }



43. The most primitive operations are faster than function calls:
Var min = Math. min (a, B); A. push (v); use var min = a <B? A B; A [A. length] = v;



44. Pay attention to the beautiful and readable code during coding:

45. JavaScript is awesome: Best Resources To Learn JavaScript












 

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.