24 practical suggestions for beginners of JavaScript [TUTS +]

Source: Internet
Author: User

Note: This document uses the Firebug console object multiple times. For details, refer to the Firebug Console API. For more details about firebug, click here.
1. Replace = with =

There are two different equal operators in JavaScript: ===|! ==And ==|! =. In contrast, the former is more recommendable. Use the former as much as possible. Reference:

"If two comparison objects share the same type and value, = true is returned ,! = False is returned ."

-JavaScript: The Good Parts
However, if the = and! =, You may encounter unexpected problems when operating on different data types. Before equality determination, JavaScript tries to convert them into strings, numbers, or Boolean values.

2. Avoid using Eval Functions

The Eval function uses a string as a parameter and executes the string as a JavaScript statement to return the result (for reference ).

This function not only reduces the execution efficiency of your script, but also greatly increases the security risk, because it gives too much rights as text parameters. Never use it!

3. Do not use Quick writing

Technically, you can omit most of the curly arc and semi-colon. Most browsers can correctly execute the following statements: Copy content to clipboardCode: if(someVariableExists)
   x = false
However, if so: Copy content to clipboardCode: if(someVariableExists)
   x = false
   anotherFunctionCall();
You may think it is equal to the following statement: Copy content to clipboardCode: if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}
Unfortunately, this is not the case. The reality is that it is equivalent: Copy content to clipboardCode: if(someVariableExists) {
   x = false;
}
anotherFunctionCall();
As you noted, the beautiful indentation cannot replace this gorgeous curly arc. In all cases, please clearly write curly braces and semicolons. It can be omitted occasionally when there is only one line of statements, although this is not recommended below: Copy content to clipboardCode: if(2 + 2 === 4) return 'nicely done'; Think about the future, child.

Suppose that you need to add more commands for this if statement in the future development process? Why don't you add brackets?

4. Make good use of JS Lint

JSLint is a debugger written by Douglas Crockford. You only need to paste your code to quickly scan for any obvious errors and problems. Reference:
"JSLint scans the received code. Locate the problem, describe the problem, and give the approximate location in the source code. Possible problems include but are not limited to syntax errors, although syntax errors are indeed the most common. JSLint will also use
It is customary to check the formatting style and structure errors of the Code. Scanning through JSLint does not guarantee that your program is completely correct. It just provides you with an extra pair of eyes for error detection ."


-JSLint document
Before you complete the code, put it in JSLint and check it to quickly eliminate your unintentional experience.

5. Load the script at the bottom of the page

As shown in:


Remember-we have to do everything possible to ensure that the page loading speed on the client is as fast as possible. When the script is not loaded, the browser cannot load the rest of the page.

If your JS file only adds some additional functions-for example, bind an event to click a link-that can be done after page loading is complete. Put the JS file at the end of the page, Before the end tag of the body, it is best to do so.

A better way of writing is Copy content to clipboardCode: <P> super brother is the most handsome man in the world. Benhuoer.com is the best blog in the world. </P>
<Script type = "text/javascript" src = "path/to/file. js"> </script>
<Script type = "text/javascript" src = "path/to/anotherFile. js"> </script>
</Body>
</Html> <! -- 0 --> <! -- 1 -->
6. Declare variables outside the For statement

When you need to execute lengthy for statements, do not let the JavaScript engine repeat unnecessary operations every time. For example:

This is not good Copy content to clipboardCode: for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}
This code re-defines the length of the array every time and traverses the DOM to find the container element. This is too silly!

This is much better. Copy content to clipboardCode: var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}
I want to leave a message to improve this code! You are welcome to leave a message for discussion!

7. quickly build strings

When you want to perform loop operations on an array or object, don't worry about the for statement of a table of talents. Let's get creative! Obviously there are many faster methods: Copy content to clipboardCode: var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
Reference:
"You don't have to bother you with so much red tape; you just trust me once (or you can try it on your own)-this is really the fastest way to find it!

Do not worry about the abstract behind it. Generally, it is much faster than the elegant methods !"

-James Padolsey, james.padolsey.com
8. Reduce global variablesReference:
"Putting all the messy footprints you step on the whole under one person can significantly reduce the possibility of conflicts with other applications, gadgets, or JS libraries ."

-Douglas Crockford
Copy content to clipboardCode: var name = 'Jeffrey';
var lastName = 'Way';
function doSomething() {...}
console.log(name); // Jeffrey -- or window.name
Better Writing Copy content to clipboardCode: var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey
Note: how can we dramatically classify "messy footprints" under "DudeNameSpace.

9. write comments

You may feel unnecessary at first, but believe me, you will Proactive thinkingWrite the comments of the Code as much as possible. When you look back at a project a few months later, it turns out that it is hard to remember what your mind was thinking when you wrote something. Isn't that frustrating? Or, what if a colleague wants to revise your code? Be sure to add comments to important parts of your code. Copy content to clipboardCode: // Traverse the array and output their names
For (var I = 0, len = array. length; I <len; I ++ ){
Console. log (array );
}
10. Try incremental Enhancement

Be sure to provide an alternative for cases where JavaScript is not enabled. You may think, "most of my visitors use JavaScript, so I don't have to worry about it ". In this case, you are wrong!

Have you ever tried to see what your pretty slide looks like when JavaScript is disabled? (You can download the Web Developer ToolBar to complete this task easily .) Once disabled, your website may lose its availability! Experience: at the beginning of development, you always design your website based on no JavaScript, and then proceed. Progressive Function EnhancementAnd carefully change your layout.

11. Do not pass the string to "setInterval" or "setTimeout"

Take a look at the following code: Copy content to clipboardCode: setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
Not only is execution not efficient, but it also has the same high risk as eval functions. Do not pass the string to setInterval or setTimeout. The proper method is to pass a function name: Copy content to clipboardCode: setInterval(someFunction, 3000); 12. Do not use the with statement

At first glance, the "with" statement seems quite useful. It is used to set the scope of code in a specific object. Its basic usage is to provide a quick way to process elements in an object. For example: Copy content to clipboardCode: with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}
-Equivalent- Copy content to clipboardCode: being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;
Unfortunately, the test shows that if you want to insert a new member to an object, with performs very poorly and runs very slowly. The alternative is to declare a variable: Copy content to clipboardCode: var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;
13. Use {} instead of New Object ()

There are multiple ways to create objects in JavaScript. The most traditional method is the new statement, as follows: Copy content to clipboardCode: var o = new Object();
o.name = 'Benhuoer';
o.lastName = 'Yang';
o.someFunction = function() {
   console.log(this.name);
}
However, this method is too bad to read. I strongly recommend that you use the following more robust text style:

Better Writing Copy content to clipboardCode: var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};
Note: If you want to create an empty object, you can use: Copy content to clipboardCode: var o = {};Reference:
"Objects literals" helps us write code that supports many features and is highly relevant and concise. There is no need to directly call the new statement, and then maintain the correct sequence between the declared variables and the statements that pass the variables, and so on ." Dyn-web.com
14. Use [] instead of New Array ()

Use the same type when creating an array.

Practical Writing Copy content to clipboardCode: var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';
Better Writing Copy content to clipboardCode: var a = ['Joe','Plumber'];Reference:
"One of the Common Errors in JavaScript programming is that objects are used when arrays are used, but arrays are used when objects are used. The rule is actually very simple: when the attribute name is a small continuous integer, you should use an array. In other cases, use the object ." -Douglas Crockford
15. long column variable declaration? Do not write so many var values. Use a comma. Copy content to clipboardCode: var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';
Better Writing Copy content to clipboardCode: var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';
... It is self-evident. I don't know if this can improve the code execution speed, but it does make your code much cleaner.

17. Remember to write a semicolon

Most browsers allow you to skip the last semicolon: Copy content to clipboardCode: var someItem = 'some string'
function doSomething() {
  return 'something'
}
As we have said before, doing so will cause potential bigger and harder-to-find problems:

Better Writing Copy content to clipboardCode: var someItem = 'some string';
function doSomething() {
  return 'something';
}
18. "For in" Statement

When traversing objects, you may find that you still need to obtain method functions. In this case, remember to package an if statement for your code to filter information. Copy content to clipboardCode: for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}
Taken from [/I] [I] Douglas Crockford: [/I] [I] JavaScript: The Good Parts

19. Use the "Timer" function of Firebug to optimize your code

Do you want to quickly learn about an operation? Use the timer function of Firebug to record the results. Copy content to clipboardCode: function TimeTracker(){
console.time("MyTimer");
for(x=5000; x > 0; x--){}
console.timeEnd("MyTimer");
}
20. Read, read, read ...... Read, Read, Read...

Although I am a Web development blog (like this !) But before eating and going to bed BooksIt seems that you have no choice ~ Put a good Web development book on your bedside table! The following books are my favorites:


  • Object-Oriented JavaScript (no Chinese version currently)
  • JavaScript: The Good Parts (Chinese Version)
  • Learning jQuery 1.3 (no Chinese version yet, but you can check the Chinese version of the old version)
  • Learning JavaScript (Chinese Version)


Read them ...... Read it multiple times! I am still reading.

21. Self-determination Functions

Compared with calling a function, it is very simple and convenient to automatically execute a function when loading the page or when a parent function is called. You only need to package your function in your parent and then add an extra bracket. In essence, this bracket triggers your defined function (learn more ). Copy content to clipboardCode: (function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();
22. Native JavaScript is always faster than code library.

JavaScript libraries such as jQuery and Mootools can save a lot of time for you to write code, especially when AJAX operations are required. But remember, as long as your code is properly written, native JavaScript will always be faster than Billy's code library.

JQuery's "each" method is very convenient for loop operations, but the use of the original for statement is always much faster.

23. Crockford's JSON. Parse

Although JavaScript 2 has a built-in JSON processor, we still need to implement it at the time of writing this article. Douglas Crockford, the creator of JSON, has already created a directly usable processor for us. You can download it here.

Import this code to create a new JSON Global Object and process your. json file. Copy content to clipboardCode: var response = JSON.parse(xhr.responseText);
var container = document.getElementById('container');
for(var i = 0, len = response.length; i < len; i++) {
container.innerHTML += '<li>' + response.name + ' : ' + response.email + '</li>';
}
For more information about JSON, see.

24. Remove "Language"

Many years ago, language was a required attribute for each script Tag: Copy content to clipboardCode: <script type="text/javascript" language="javascript">
...
</script>
But now, this attribute has not been used for a long time ...... So, delete it!

That's all, friends ~

That's all. This is my 24 tips for beginners of JavaScript. Dear friends, what do you think? Do you have any quick tips? Thank you for your patience.

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.