JavaScript Novice 24 practical advice [Tuts+]_javascript Tips

Source: Internet
Author: User
Tags script tag setinterval
Note: The Firebug console object is used many times in this article, please refer to Firebug Console API。 For a more detailed description of Firebug, please Bash here。
1. = = = Replace = = = =

There are two different equality operators in JavaScript: ===|! = = and ==|! = By contrast, the former is more worthy of recommendation. Please try to use the former.

Reference:

"If two comparison objects have the same type and value, = = = Return true,!== returns FALSE." ”

–javascript:the Good Parts
However, if you use = = and!=, you may encounter some unexpected problems when manipulating different data types. JavaScript attempts to convert them to a string, number, or Boolean before making equality judgments.

2. Avoid using the Eval function

The Eval function takes a string as an argument and executes the string as a JavaScript statement, returning the result ( Reference)。

Not only does this function reduce the execution efficiency of your script, but it also greatly increases the security risk because it gives too much power to the arguments as text. Don't use it!

3. Do not use the quick wording

Technically, you can omit most of the curly braces and the end of the semicolon, and most browsers will correctly execute the following statement:
Copy Content to Clipboard

Code:

if(someVariableExists)
   x = false
However, if this is the case:
Copy Content to Clipboard

Code:

if(someVariableExists)
   x = false
   anotherFunctionCall();
You might think it's the same as the following statement:
Copy Content to Clipboard

Code:

if(someVariableExists) {
   x = false;
   anotherFunctionCall();
}
Unfortunately, that is not the case. The reality is that it is equivalent to:
Copy Content to Clipboard

Code:

if(someVariableExists) {
   x = false;
}
anotherFunctionCall();
As you can see, the beautiful indentation is no substitute for this gorgeous curly bracket. In all cases, write clearly the curly braces and the end of the sentence semicolon. It can be omitted occasionally when there is only one line of statements, although it is highly deprecated to do so:
Copy Content to Clipboard

Code:

if(2 + 2 === 4) return 'nicely done';
think more about the future, son.

Suppose you need to add more commands to this if statement in the future development process? And you're not going to have to add the parentheses?

4. Make good use of JS Lint

JSLintis a debugger written by Douglas Crockford. All you have to do is post your code and it will quickly scan you for any obvious bugs and problems.

Reference:

"JSLint scans for incoming code. Find the problem, describe the problem, and give the approximate location in the source code. The problems that can be found include, but are not limited to, grammatical errors, although grammatical errors are indeed the most common. JSLint will also use
Conventional habits Check the formatting style of the code, as well as the structural errors. Scanning through the JSLint does not guarantee that your program will be completely correct. It just provides you with an extra pair of wrong eyes to find. ”


–jslint Document
Before you complete the code, put it in the jslint to check it out and quickly eliminate the unintentional.

5. Load script at bottom of page

As the following illustration shows:


Remember-we have to make every effort to ensure that the client's page loads as fast as possible. When the script is not loaded, the browser cannot load the remainder of the page.

If your JS file just adds some extra functionality--for example, to click on a link binding event--that can be done after the page is basically loaded. Put the JS file to the end of the page, the body of the end tag, this is best.

the better way to do this is
Copy Content to Clipboard

Code:

<p>超哥是世界上最帅的人。benhuoer.com是世界上最好看的博客。</p>
<script type="text/javascript" src="path/to/file.js"></script>
<script type="text/javascript" src="path/to/anotherFile.js"></script>
</body>
6. Declare a variable outside of a for statement

When you need to execute a lengthy for statement, do not let the JavaScript engine repeat the unnecessary actions each time. For example:

It's not good .
Copy Content to Clipboard

Code:

for(var i = 0; i < someArray.length; i++) {
   var container = document.getElementById('container');
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}
This code will redefine the length of the array each time, traversing the DOM to find the container element--that's silly!

that's better.
Copy Content to Clipboard

Code:

var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}
I would like to give a message to improve the code of the people of the extra surprise! Welcome to the message discussion!

7. Quickly build strings

To do a loop on an array or object, don't dwell on the handsome for statement, get some ideas out! There are many quicker ways to do it:
Copy Content to Clipboard

Code:

var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

Reference:

"There's not so much red tape bothering you, you just trust me once (or you can try it yourself)--it's really the quickest way to find out!"

Use a little Earth method, also regardless of what happened behind it what abstract things, usually the soil method is more efficient than those elegant way! ”

–james Padolsey, james.padolsey.com
8. Reduce global Variables

Reference:

"Put your foot in the overall situation of those messy footprints are attributed to one person, can significantly reduce the use of other applications, gadgets or JS library conflict possibilities." ”

–douglas Crockford
Copy Content to Clipboard

Code:

var name = 'Jeffrey';
var lastName = 'Way';
function doSomething() {...}
console.log(name); // Jeffrey -- or window.name
a better way to spell
Copy Content to Clipboard

Code:

var DudeNameSpace = {
   name : 'Jeffrey',
   lastName : 'Way',
   doSomething : function() {...}
}
console.log(DudeNameSpace.name); // Jeffrey
Notice how we dramatically put "messy footprints" under the "Dudenamespace" object.

9. Write a good note

You may feel unnecessary at first, but believe me, you will Take the initiative toTry to write the comments of the code as well as possible. When you look back at a project a few months later, it turns out it's hard to remember what your brain is thinking when you write something, is that frustrating? Or, what if a co-worker wants to revise your code? Be sure to annotate important parts of your code.
Copy Content to Clipboard

Code:

// 遍历数组,输出各自名称
for(var i = 0, len = array.length; i < len; i++) {
   console.log(array);
}
10. Try Progressive Enhancement

Be sure to remember to provide an alternative to JavaScript-not-enabled scenarios. You might think, "most of my visitors have JavaScript enabled, and I don't have to worry about it." In that case, you would be mistaken!

Have you ever tried to see what your pretty sliders are like when you disable JavaScript? (You can download Web Developer ToolBarFinish the task with ease. After disabling your site may be completely out of usability! Experience: You always design your site without JavaScript in the early stages of development. Progressive function Enhancement, and carefully change your layout.

11. Do not pass strings to "setinterval" or "settimeout"

Look at the following code:
Copy Content to Clipboard

Code:

setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
Not only is execution not efficient, but it has the same high risk as the Eval function. Never pass strings to SetInterval and settimeout. The appropriate thing to do is to pass a function name:
Copy Content to Clipboard

Code:

setInterval(someFunction, 3000);
12. Do not use the WITH statement

Under the initial knowledge, the "with" statement seems quite useful. It is used to set the scope of code within a specific object. Its basic usage is to provide a quick notation for processing elements into objects. For example:
Copy Content to Clipboard

Code:

with (being.person.man.bodyparts) {
   arms = true;
   legs = true;
}
– Equivalent to-
Copy Content to Clipboard

Code:

being.person.man.bodyparts.arms = true;
being.person.man.bodyparts.legs= true;
Unfortunately, the tests showed that if you were to insert a new member for the object, the with performance was very bad and it was performing very slowly. The alternative is to declare a variable:
Copy Content to Clipboard

Code:

var o = being.person.man.bodyparts;
o.arms = true;
o.legs = true;
13. Use {} instead of new Object ()

There are several ways to create new objects in JavaScript. The most traditional method is the new statement, as follows:
Copy Content to Clipboard

Code:

var o = new Object();
o.name = 'Benhuoer';
o.lastName = 'Yang';
o.someFunction = function() {
   console.log(this.name);
}
However, this method is worse to read. I strongly recommend that you use the following type of more robust writing style:

a better way to spell
Copy Content to Clipboard

Code:

var o = {
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};
Note that if you want to create a new empty object, you can do so with {}:
Copy Content to Clipboard

Code:

var o = {};

Reference:

The object literal (Objects literals) helps us write code that supports many features, but also has strong, concise, straightforward relationships. There is no need to call the new statement directly, and then bother to maintain the correct order between the statements declaring the variables and passing them, and so on. "– dyn-web.com
14. Use [] without the new Array ()

The same type of application when creating a new array.

the written wording of the line
Copy Content to Clipboard

Code:

var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';
a better way to spell
Copy Content to Clipboard

Code:

var a = ['Joe','Plumber'];

Reference:

"One of the most common mistakes in JavaScript programming is when you use an array with an object, but you use an array when you use the object." The rule is simple: when the property name is a small sequential integer, you should use an array. Other cases, using objects. "–douglas Crockford
15. A long list of variable declarations? Don't write so many Var, with commas.
Copy Content to Clipboard

Code:

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';
a better way to spell
Copy Content to Clipboard

Code:

var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';
... It is self-evident. I don't know if this will improve the speed of code execution, but it does make your code a lot cleaner.

17. Chivan Remember to write a semicolon

Most browsers allow you to write a semicolon without the end of the sentence:
Copy Content to Clipboard

Code:

var someItem = 'some string'
function doSomething() {
  return 'something'
}
As has been said before, this will create potentially bigger and more difficult to spot problems:

a better way to spell
Copy Content to Clipboard

Code:

var someItem = 'some string';
function doSomething() {
  return 'something';
}
"for in" statement

As you traverse the object, you may find that you also need to get the method function. So in this case, be sure to remember to give your code package a layer of if statement to filter the information.
Copy Content to Clipboard

Code:

for(key in object) {
   if(object.hasOwnProperty(key) {
      ...then do something...
   }
}
quoted from [/i][i] Douglas Crockford: [/i][i] javascript:the good Parts

19. Use Firebug's "Timer" function to optimize your code

Want to easily get a quick idea of when an operation is available? Use the Firebug timer function to record the results.
Copy Content to Clipboard

Code:

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!) Super fans, but before eating and sleeping except to see BooksThere seems to be no other choice ~ on your bedside table a good Book of Web Development! The following list is my favorite:


    • object-oriented JavaScript(no Chinese version)
    • javascript:the Good Parts( Chinese version )
    • Learning jQuery 1.3(no Chinese version, but you can look at the old version of the Chinese version)
    • Learning JavaScript( Chinese version )


Read them ... Repeated reading many times! I'm still reading it now.

21. The function of self-determination

It is a simple and convenient way to make a function run automatically when the page is loaded or when a parent function is invoked, compared to calling a function. All you have to do is wrap your function within your parents and add an extra bracket that essentially triggers the function you define ( Learn More)。
Copy Content to Clipboard

Code:

(function doSomething() {
   return {
      name: 'jeff',
      lastName: 'way'
   };
})();
22. Native JavaScript is always faster than using a code base

JavaScript libraries such as jquery and MooTools can save you a lot of time writing code-especially when AJAX is needed. But remember, as long as your code is properly written, native JavaScript will always execute faster than using code libraries.

The "Each" method of jquery is handy for looping, but it's always a lot quicker to use the original for statement.

Crockford's JSON. Parse

Although JavaScript 2 builds a JSON processor, we need to do it ourselves when writing this article. The creator of Douglas Crockford,json has created a processor that we can use directly. Here you can Download。

By importing this code, you can create a new JSON global object and then process your. json file.
Copy Content to Clipboard

Code:

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 JSON, see More Information。

24. Remove "Language"

Many years ago, language was still a prerequisite for each script tag:
Copy Content to Clipboard

Code:

<script type="text/javascript" language="javascript">
...
</script>
But now, this attribute has not been used for a long time ... So, delete the count!

that's it, folks.

That's it, that's the 24 tips I give to JavaScript beginners. Dear friends, What's your opinion? Do you have any quick tips? Thank you for your patience in reading.

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.