24 Practical Tips for beginners in JavaScript __java

Source: Internet
Author: User
Tags script tag setinterval

This article lists 24 suggestions to make your code writing process easier and more efficient. Maybe you're a JavaScript beginner, just finishing up your Hello world, and there's a lot of tips that will be useful to your work; maybe some of the tricks you already know, try a quick glance and see if you can find something new.

Note: The Firebug console object is used many times in this article, please refer to the Firebug console API. For a more detailed description of Firebug, please bash here.

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

"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 a parameter 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:

. if (somevariableexists)
x = False

However, if this is the case:

. if (somevariableexists)
x = False
Anotherfunctioncall ();

You might think it's the same as the following statement:

if (somevariableexists) {
x = false;
Anotherfunctioncall ();
}

Unfortunately, that is not the case. The reality is that it is equivalent to:

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:

if (2 + 2 = = 4) Return to ' nicely done ';

Think more about the future, son.
Suppose you need to add more commands to this if statement in the future development process. You're not going to have to add the brackets.

4. Make good use of JS Lint

JSLint is 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.

"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 customary custom to check the formatting style of the code, as well as 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:


Click to enlarge

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.

A better way to do this is to:

<p> Super Brother is the most handsome man in the world. Benhuoer.com is the most beautiful 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>

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:

This is not good:

for (var i = 0; i < somearray.length; i++) {
var container = document.getElementById (' container ');
container.innerhtml + = ' My number: ' + i;
Console.log (i);
}

This code redefine the length of the array each time, traversing the DOM to find the container element every time--that's silly.

That's better:

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 give the message to improve the code for the person of extra surprise. You are welcome to leave a message to discuss.

7. Quickly build strings

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

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

"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 so far."
Use a little Earth method, and forget what is happening behind it, usually the soil is much quicker than the elegant approach. "–james Padolsey, james.padolsey.com

8. Reduce global Variables

"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

var name = ' Jeffrey ';
var lastName = ' Way ';

function dosomething () {...}

Console.log (name); Jeffrey--or Window.name

Better way to do it:

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

It may not be necessary at first, but trust me, you will be willing to write the code as much as possible in the future. When you go back to a project a few months later, it turns out it's hard to remember what your brain is thinking when you write something, and it's frustrating. Or, if a co-worker wants to revise your code. Be sure to annotate important parts of your code.

Cycle through array and echo out each name.
for (var i = 0, len = Array.Length i < len; i++) {
Console.log (Array[i]);
}

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 the Web Developer ToolBar easily complete this task.) After disabling, your site may be completely out of usability. Experience: The early stages of development are always to design your site without JavaScript, and then incrementally function to enhance and carefully change your layout.

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

Look at the following 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:

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:

With (Being.person.man.bodyparts) {
Arms = true;
Legs = true;
}

Equivalent to:

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:

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:

var o = new Object ();
O.name = ' Jeffrey ';
O.lastname = ' Way ';
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:

Better way to do it:

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

var o = {};

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 wording of the line:

var a = new Array ();
A[0] = "Joe";
A[1] = ' Plumber ';

Better way to do it:

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

"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.

var Someitem = ' some string ';
var Anotheritem = ' another string ';
var onemoreitem = ' One more string ';

Better way to do it:

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 clean. Chivan Remember to write a semicolon

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

var Someitem = ' Some string '
function dosomething () {
Return ' something '
}

As has been said before, this will create potentially bigger and more difficult to spot problems:

Better way to do it:

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.

For (key in object) {
if (Object.hasownproperty (key) {
... then do something ...
}
}

quoted by Douglas Crockford: 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 in place. Use the Firebug timer function to record the results.

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 (just like this one.) Super fan, but before eating and sleeping in addition to reading seems to have no choice ~ on your bedside table on the web development of a good book it. 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 ... Read it many times over and over again. 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, which in essence triggers the function you define (learn more).

(function dosomething () {
return {
Name: ' Jeff ',
LastName: ' Way '
};
})();

native JavaScript is always faster than using code libraries.

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. You can download it here.

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

For more information about JSON, see more.

24. Remove "Language"

Many years ago, language was still a prerequisite for each script tag:

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


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[i].name + ': ' + response[i].email + ' </li> ';
}

if (somevariableexists) {
x = false;
}
Anotherfunctioncall ();

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.