Complete Javascript skills for Web Development

Source: Internet
Author: User

Complete Javascript skills for Web Development

JavaScript is a world-class programming language that can be used for Web development, mobile application development (PhoneGap, Appcelerator), and server-side development (Node. js And Wakanda. JavaScript is the first language in the programming world for many new users. It can be used to display a simple prompt box in the browser, or to control the robot through nodebot or nodruino. Developers who can write JavaScript code with clear structures and high performance have become the most sought after candidates in the Recruitment Market.

In this article, I will share some JavaScript tips, tips, and best practices. They are applicable to both the browser's JavaScript engine and the server-side JavaScript interpreter.

The sample code in this article passes the test on the latest version of Google Chrome 30 (V8 3.20.17.15.

 1. When assigning values to variables for the first time, you must use the var keyword.

Variables are directly assigned without declaration. By default, they are used as a new global variable. Avoid using global variables whenever possible.

  2. Use = replace =

= And! = The operator will automatically convert the data type as needed. But = and! = No, they compare values and data types at the same time, which also makes them equal to = and! = Fast.

 [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. The logical results of underfined, null, 0, false, NaN, and null strings are all false.

  4. Use a semicolon at the end of the line

In practice, it is best to use a semicolon. If you forget to write it, The JavaScript interpreter will be automatically added in most cases. For more information about the use of semicolons, see the truth about semicolons in JavaScript.

  5. Use the object constructor

  function Person(firstName, lastName){this.firstName = firstName;this.lastName = lastName;  }  var Saad = new Person("Saad", "Mousliki");

6. Use typeof, instanceof, and contructor with caution.

• Typeof: JavaScript unary operator, used to return the original type of the variable in the form of a string. Note that typeof null also returns the object. Most object types (Array, time Date, etc) will also return the object
• Contructor: Internal prototype attribute, which can be rewritten through code
• Instanceof: JavaScript operator, which is searched by the constructor in the prototype chain. If it is found, true is returned. Otherwise, false is returned.

Var arr = ["a", "B", "c"]; typeof arr; // return "object" arr instanceof Array // true arr. constructor (); // []

 7. Use self-called Functions

A Function is automatically executed after it is created. It is generally called a Self-Invoked Anonymous Function or an Immediately Invoked Function Expression ). The format is as follows:

(Function () {// The Code put here will be automatically executed}) (); (function (a, B) {var result = a + B; return result ;}) (10, 20)

 8. Randomly retrieve members from the array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];var randomItem = items[Math.floor(Math.random() * items.length)];

 9. Obtain random numbers within a specified range

This function is especially useful when generating false data for testing, such as the number of salaries within a specified range.

var x = Math.floor(Math.random() * (max - min + 1)) + min;

10. Generate a number array from 0 to the specified value

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

 11. generate random letters and numbers

  function generateRandomAlphaNum(len) {var rdmString = "";for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));return rdmString.substr(0, len);  }

  12. disrupt the order of number Arrays 

Var numbers = [5,458,120,-215,228,400,122 205,-85411]; numbers = numbers. sort (function () {return Math. random ()-0.5});/* The numbers array will be similar to [120, 5,228,-215,400,458,-85411,122] */

Here we use the array sorting function built in JavaScript. A better way is to use special code (such as the Fisher-Yates algorithm). For details, see the discussion on StackOverFlow.

 13. Remove spaces from strings

Java, C #, PHP, and other languages all implement special String space-removing functions, but JavaScript does not. You can use the following code to function a trim function for the String object:

String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};

The new JavaScript Engine already has the native Implementation of trim.

  14. appending between Arrays

Var array1 = [12, "foo", {name "Joe"},-2458]; var array2 = ["Doe", 555,100]; Array. prototype. push. apply (array1, array2);/* the value of array1 is [12, "foo", {name "Joe"},-2458, "Doe", 555,100] */

  15. convert an object to an array

var argArray = Array.prototype.slice.call(arguments);

  16. Verify if it is a number

function isNumber(n){return !isNaN(parseFloat(n)) && isFinite(n);  }

  17. Verify whether it is an array

  function isArray(obj){return Object.prototype.toString.call(obj) === '[object Array]' ;  }

However, if the toString () method is overwritten, it will not work. You can also use the following method:

Array.isArray(obj); // its a new Array method

If frame is not used in the browser, you can also use instanceof. However, if the context is too complex, errors may occur.

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); // The constructor of [a, B, 10] // myArray has been lost, the instanceof result will be abnormal // The constructor cannot share the arr instanceof Array across frames; // false

 18. obtain the maximum and minimum values in the array.

 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 directly delete or remove elements from the array.

If you directly use delete For array elements, the elements are not deleted, but are set to undefined. Splice should be used to delete array elements.

Avoid:

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/* The items result is [12,548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe ", 2154,119] */

But should:

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 result: [12,548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,119]

Delete can be used to delete attributes of an object.

  21. Use the length attribute to truncate the array.

In the preceding example, The length attribute is used to clear the array. It can also be used to truncate the array:

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];   myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

At the same time, if you increase the length attribute, the length value of the array will increase, and undefined will be used to fill the new element. Length is a writable attribute.

myArray.length = 10; // the new array length is 10myArray[myArray.length - 1] ; // undefined

  22. Use logic in conditions and

var foo = 10;   foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();  foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

Logical or can also be used to set default values, such as the default values of function parameters.

  function doSomething(arg1){arg1 = arg1 || 10; // arg1 will have 10 as a default value if it's not already set  }

  23. Make the map () function method cycle the data.

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

24. Retain the specified decimal places

var num =2.443242342;  num = num.toFixed(4); // num will be equal to 2.4432

Note that toFixec () returns a string, not a number.

  25. Floating Point computing problems

  0.1 + 0.2 === 0.3 // is false  9007199254740992 + 1 // is equal to 9007199254740992  9007199254740992 + 2 // is equal to 9007199254740994

Why? Because 0.1 + 0.2 equals 0.30000000000000004. JavaScript numbers follow the IEEE 754 standard and are represented by 64-bit floating point decimals. For details, see how the numbers in JavaScript are encoded.

You can solve this problem by using toFixed () and toPrecision.

  26. Check the object attributes through the for-in Loop

The following usage prevents objects from entering the prototype attribute during iteration.

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. temporary storage of variables for calculation and query

In the jQuery selector, You can temporarily store the entire DOM element.

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

  29. Check the input isFinite () parameters in advance

IsFinite (0/0); // false isFinite ("foo"); // false isFinite ("10"); // true isFinite (10 ); // true isFinite (undefined); // false isFinite (null); // true, which deserves special attention.

  30. Avoid using negative numbers in the array for indexing.

 var numbersArray = [1,2,3,4,5];   var from = numbersArray.indexOf("foo") ; // from is equal to -1   numbersArray.splice(from,2); // will return [5]

Note that the index parameter passed to splice should not be a negative number. When it is a negative number, the elements will be deleted from the end of the array.

31. Use JSON for serialization and deserialization

Var person = {name: 'saad', age: 26, department: {ID: 15, name: "R & D" }}; var stringFromPerson = JSON. stringify (person);/* stringFromPerson returns "{" name ":" Saad "," age ": 26," department ": {" ID ": 15, "name": "R & D"} "*/var personFromString = JSON. parse (stringFromPerson);/* the value of personFromString is the same as that of the person object */

 32. Do not use eval () or function Constructor

Eval () and Function consturctor have high overhead. Each call, the JavaScript engine must convert the source code into executable code.

 var func1 = new Function(functionCode);  var func2 = eval(functionCode);

  32. Do not use eval () or function Constructor

Eval () and Function consturctor have high overhead. Each call, the JavaScript engine must convert the source code into executable code.

var func1 = new Function(functionCode);  var func2 = eval(functionCode);

33. Avoid using ()

With () can be used to add variables to the global scope. Therefore, if there are other variables with the same name, it is easy to confuse and the second value will be overwritten.

34. Do not use for-in for Arrays

Avoid:

  var sum = 0;   for (var i in arrayNumbers) {    sum += arrayNumbers[i];   }

But:

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

Another benefit is that the I and len variables are initialized only once in the first declaration of the for loop, which is faster than the following statement:

for (var i = 0; i < arrayNumbers.length; i++)

35. Use a function instead of a string when it is passed to setInterval () and setTimeout ()

If it is passed to a string of setTimeout () and setInterval (), they will convert it in a way similar to eval, which must be slower, so do not use:

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

Instead, use:

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

  36. Use switch/case to replace a large stack of if/else

When judging that there are more than two branches, it is faster to use switch/case, and it is more elegant and more conducive to the Code Organization. Of course, if there are more than 10 branches, do not use switch/case.

 37. use numeric intervals in switch/case

In fact, the case condition in switch/case can also be written 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); // "Baby" is returned"

   38. Use an object as the prototype of the object

In this way, you can specify an object as a parameter to create a new object based on this prototype:

function clone(object) {    function OneShotConstructor(){};   OneShotConstructor.prototype = object;    return new OneShotConstructor();  }  clone(Array).prototype ; // []

 39. HTML field conversion functions

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

 40. Do not use try-catch-finally inside the loop

The catch part in try-catch-finally assigns an exception to a variable during execution, which is constructed into a new variable in the runtime scope.

Avoid:

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

However, we should:

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 when using XMLHttpRequests

When XMLHttpRequests is executed, when there is no response for a long time (such as a network problem), the connection should be aborted. You can use setTimeout () to do this:

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

At the same time, you must note that do not initiate multiple XMLHttpRequests requests at the same time.

  42. Processing WebSocket timeout

Generally, after a WebSocket connection is created, if there is no activity within 30 seconds, the server will process the connection timeout, And the firewall can also process the timeout for connections that are not active in a unit cycle.

To prevent this situation, you can send an empty message to the server at intervals. The following two functions can be used to achieve this requirement. One is used to maintain the active state of the connection, and the other is used to end the State.

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 () function can be placed at the end of the onOpen () method connected to WebSocket, and cancelKeepAlive () is placed at the end of the onClose () method.

  43. Time note: the original operator is faster than the function call, And VanillaJS is used.

For example, do not:

 var min = Math.min(a,b);  A.push(v);

This can be replaced:

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

  44. Pay attention to the code structure during development. Check and compress JavaScript code before going online.

Don't forget to use a code beautification tool when writing code. Use JSLint (a syntax check tool) and compress code before going online (for example, using JSMin ). Note: currently Code compression is generally recommended UglifyJS (https://github.com/mishoo/UglifyJS2)

  45. JavaScript is profound and profound, and there are some good learning resources here

• Code Academy resources: http://www.codecademy.com/tracks/javascript
• Eloquent JavaScript written by Marjin Haverbekex: http://eloquentjavascript.net/
• Advanced JavaScript written by John Resig: http://ejohn.org/apps/learn/

Articles you may be interested in:
  • PHP tips: How to Use JS and CSS optimization tool Minify
  • Tips for inserting an element at a specified position in a specific index of a JS Array
  • Using Chrome to debug JavaScript breakpoint settings and debugging skills
  • How to Use the alert () function in JavaScript
  • Tips for Google browser JavaScript debugging

Related Article

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.