24 Best practices that JavaScript people should know about when they first start learning

Source: Internet
Author: User
Tags script tag

Original: JavaScript Best Practices for Beginners

(note: read the original time did not pay attention to the publication date, think good translation, translation to JSON.parse that section think a bit incorrect road to find is published in 2009 article, just still good.

In addition, despite the 24 best practices, there are actually only 23 articles. I do not know how the original author missed a piece.

1. prefer = = =. rather than = =

JavaScript uses two equality operators: === , !== and == , != .

It is common to think that the best practice to do is to use the previous set of Operators.

"if the type and value of the two operands are the same, then === the comparison results are true." !==The comparative result is False. "---JavaScript language essence (javascript:the Good Parts)

however, if == you use and != , when comparing the operands of different types, you will encounter Problems. In such a case, this set of operators attempts to do a useless cast on the value of the Operand.

2. Eval is a bad Pronoun.

For those of you who are unfamiliar with Javascript. The function "evel" allows us to access the JavaScript compiler. We can get the result of running the string by passing a string parameter to "eval".

This will not only greatly reduce the performance of your script. It also creates a huge security risk because it gives too much of the ability to pass in plain Text. Avoid using the Eval function as much as you Can.

3. Don't lazy hands

technically, you might be lucky to omit most curly braces and semicolons.

Most browsers can interpret the code snippet correctly, such as the Following:

if(someVariableExists)    x = false

However. Consider this code again:

if(someVariableExists)    x = false    anotherFunctionCall();

Someone might think that the last piece of code is equivalent to:

if(someVariableExists) {    x = false;    anotherFunctionCall();}

Very Unfortunate. He was wrong.

In fact, it is intended to be:

if(someVariableExists)    x = false;anotherFunctionCall();

You should also notice that the indentation in the code mimics the function of the curly Braces.

Needless to do, this is a very scary practice that should be avoided in any case. The only way to omit curly braces is in a single line of statements, but even this is a very controversial situation.

if(2 + 2 === 4) return ‘nicely done‘;

Always think about the future

Suppose you need to add a lot of other commands to this if statement sometime Later. What should we do then? Couldn't You're just going to rewrite this piece of Code. The bottom line in dealing with this problem is to be cautious about omitting the Wording.

4. Using JS Lint

JSLint is a debugger written by Douglas Crockford.

Simply copy your script in. It will scan your code for any obvious problems and errors at high Speed.

>

"jslint gets a copy of the JavaScript source code and then scans the Code. Assume that a problem is found. A message is returned describing the problem and the approximate location of the problem in the source Code. The problem, though often a grammatical error, is not necessarily. JSLint also looks at some style habits and structural problems. It does not prove that your code is Correct. Just provide another pair of eyes to help identify the Problem. "---jslint Documentation

Before you finish writing your script code, run a jslint on it to make sure you don't make stupid mistakes.

5. Place the script at the bottom of the page

This technique is also recommended in the previous articles in this Series. As it is also suitable here (as it's highly appropriate though), all I paste that piece of information directly here.

Remember---the main goal of this best practice is to load pages for users as quickly as Possible. When a script is Loaded. The browser continues until the entire script file is loaded to Completion. therefore, the user must wait longer for the ability to notice whatever progress.

Suppose the purpose of the JS file is to add Functionality---for example, after clicking on a button---then put those files at the bottom, before the body end Tag.

This is definitely a best practice.

A better approach

<p>And now you know my favorite kinds of corn. </p><script type="text/javascript" src="path/to/file.js"></script><script type="text/javascript" src="path/to/anotherFile.js"></script></body>
6. Declaring a variable outside of a for statement

When running a lengthy "for" statement, just let the explanation engine do the work that must be DONE.

Like what:

Bad Practice.

for(var i = 0; i < someArray.length; i++) {    var container = document.getElementById(‘container‘);    container.innerHtml += ‘my number: ‘ + i;    console.log(i);}

Note that each iteration in the code snippet above needs to check the length of the array, and each time you traverse the DOM tree to find the "container" element---how inefficient it is.

A better approach

var container = document.getElementById(‘container‘);for(var i = 0, len = someArray.length; i < len; i++) {    container.innerHtml += ‘my number: ‘ + i;    console.log(i);}

Thanks to a friend who left a comment showing how to further optimize the code block Above.

7. The quickest way to build a string

When you need to traverse an array or object, don't always use a "for" statement that you can stick to. Creatively find a high-speed solution that can be completed at Work.

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

>

"i'm not bothering you with a test benchmark, you just have to trust me (or try it yourself)---this is the quickest way to go!

"

Using native methods (for example, join ()) does not take care of what is happening behind the abstraction level, and is generally much faster than whatever non-native method. ---James padolsey, james.padolsey.com "

8. Reducing Global variables

>

"by encapsulating the global stuff into a single namespace. Can greatly reduce the probability of interacting with other applications, parts, and code Libraries. "---Douglas Crockford

var name = ‘jeffrey‘;var lastname = ‘Way‘;function doSomething() {...}console.log(name);      // Jeffrey -- or window.name

A better approach

var DudeNameSpace = {    name: ‘Jeffrey‘,    lastname: ‘Way‘,    doSometing: function() {...}}console.log(DudeNameSpace.name);    // Jeffrey

Notice how we reduced the overall "footprint" to a named ridiculous "dudenamespace" Object.

9. Stare at your code

It doesn't seem necessary at first, but please believe Me. You will want to stare at your code as well as Possible. When you return to the project a few months later. What's going to happen? Find that you simply can't remember the idea of each line of code EASILY.

or, What if one of your coworkers needs to change your code? Always. Always remember to stare at the important parts of your code.

// Cycle through array and echo out each namefor(var i = 0, len = array.length; i < len; i++) {    console.log(array[i]);}
10. Embrace Progressive Enhancement

Always consider how to deal with JavaScript disabling scenarios. You might think, "most of my web readers are javascript-enabled." So I'm not worried about this Problem. "however, it would be a huge mistake.

Have you ever taken the time to see what your beautiful slider looks like after turning off javascript? (download The web Developer toolbar to make it easier to do this.)

Maybe it will completely ruin your Website. In accordance with previous Experience. When designing your site, you should disable JavaScript if it is to be disabled.

so, once you've done that, start incrementally to enhance your page Layout.

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

consider, for example, the following code:

setInterval("document.getElementById(‘container‘).innerHTML += ‘my new number: ‘ + i", 3000);

This code is not only inefficient, but behaves the same as the "eval" Function.

Never pass strings to SetInterval and Settimeout. Instead. A function name should be Passed.

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

At first glance, The "with" statement seems to be a clever idea. The basic concept is that they can provide a shorthand way to access deep nested objects. Like what...

with (being.person.man.bodyparts) {    arms = true;    legs = true;}

Replace for example the following wording

being.person.man.bodyparts.arms = true;being.person.man.bodyparts.legs = true;

Very Unfortunate. After some testing. You will find that this shorthand is very bad when you set up a new member.

As an alternative, you should use Var.

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

There are several ways to create objects in Javascript. Perhaps the more traditional way is to use the "new" constructor, like This:

var o = new Object();o.name = ‘Jeffrey‘;o.lastname = ‘Way‘;o.someFuncion = function() {    console.log(this.name);}

However. Such a way is thought to be "bad practice" because its behavior is not what we think. Instead. I recommend that you use a more robust object literal method.

Better Notation.

var o = {    name: ‘Jeffrey‘,    lastName: ‘Way‘,    someFunction: function() {        console.log(this.name);    }};

Note that if you simply want to create an empty object, {} comes in Handy.

var o = {};

>

"object literals allow us to write code that supports very many Features. And the code is still relatively intuitive to the implementation of the Code. You do not need to call the constructor directly or maintain the correct order of the parameters passed to the function, and so On. "---dyn-web.com

14. Use [] instead of the new Array ()

The same applies to creating a new array.

A passable notation

var a = new Array();a[0] = ‘Joe‘;a[1] = ‘Plumber‘;

Better Notation.

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

>

A common mistake in JavaScript is to use an array when an array is required or when an object is Required.

The rule is very easy: you should use an array when the property name is a small sequential integer. otherwise, use the object "---Douglas Crockford

15. A long list of variables? Omit "var" keyword, use comma instead
var someItem = ‘some string‘;var anotherItem = ‘another string‘;var oneMoreItem = ‘one more string‘;

Better Notation.

var someItem = ‘some string‘,    anotherItem = ‘another string‘,    oneMoreItem = ‘one more string‘;

Quite self-evident. I don't know if there is any real speed boost here, but it makes your code more CONCISE.

16. always, Always use semicolons

technically, Most browsers agree that you omit some semicolons.

var someItem = ‘some string‘function doSomething() {    return ‘something‘}

That being said, it is a very bad practice. It can lead to bigger problems, and it's more difficult to find Them.

Better Notation.

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

You will also get a method function when iterating over the members of the Object. In order to solve the Problem. You should always wrap your code in an if statement to filter the Information.

for(key in object) {    if(object.hasOwnProperty(key)) {        ... then do something...    }}

Quote from JavaScript: the essence of language, Douglas Crockford

19. Use the Firebug "Timer" feature to optimize the code

Need a high-speed and simple way to detect how long an operation takes? Use the Firebug timer feature to record the Results.

function TimeTracker() {    console.time("MyTimer");    for(x=5000; x > 0; x--){}    console.timeEnd("MyTimer");}
20. Read. Read. Read more

I am a huge fan of web development blogs (for example, this blog!). ), but eat lunch or before Bedtime. Blogging is really not a substitute for books.

Always put a wen development book in front of your bed Table. For example, here are some of my favorite JavaScript books.

    • object-oriented JavaScript
    • JavaScript: the essence of language
    • Crazy Ajax Handouts
    • JavaScript Learning Guide

Read it a few more times.

I'm Still reading!

21. self-running function (self-executing Functions)

When the page loads or calls the parent function, compared to the calling Function. It's easier to let the function run on its own Initiative.

Simply wrap your function inside Parentheses. and add an extra pair of parentheses, which essentially calls this Function.

(function doSomething() {    return {        name: ‘jeff‘,        lastName: ‘way‘    }; })();
22. Raw (raw) JavaScript code is always running faster than using code libraries

JavaScript code libraries, such as jquery and Mootools. It can save you a lot of coding time---especially with Ajax Operations. Having said that, keep in mind that the code base is always running faster than the original JavaScript code (if the code is correct).

Jquery's "each" method is great for traversal, but using native "for" statements is always faster.

23.Crockford of Json.parse

Although JavaScript 2 should have a built-in JSON parser, we still need to do it ourselves when we write this Article.

Douglas Crockford,json creator, has implemented a parser for you to Use. Can be downloaded from here.

Simply import the script and you will get a new JSON global object that will parse Your. JSON file.

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>‘;}
24. Delete "Language"

A few years Ago. The "language" attribute is common within the script Tag.

<script type="text/javascript" language="javascript">...</script>

however, This attribute has been deprecated very early, so don't use it anymore.

That's all, Comrades.

Now you know the 24 basic techniques that the JavaScript learner should know. Have a chance to let me know your tips, too.

Thanks for Reading.

24 Best practices that JavaScript people should know about when they first start learning

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.