24 JavaScript Best Practices for Beginners

转载 2013年12月05日 21:51:13

1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts

However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.


2. Eval = Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.

Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!


3. Don’t Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

  1. if(someVariableExists)  
  2.    x = false  

However, consider this:

  1. if(someVariableExists)  
  2.    x = false  
  3.    anotherFunctionCall();  

One might think that the code above would be equivalent to:

  1. if(someVariableExists) {  
  2.    x = false;  
  3.    anotherFunctionCall();  
  4. }  

Unfortunately, he’d be wrong. In reality, it means:

  1. if(someVariableExists) {  
  2.    x = false;  
  3. }  
  4. anotherFunctionCall();  

As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

  1. if(2 + 2 === 4) return 'nicely done';  

Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.


4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

“JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.” 
– JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven’t made any mindless mistakes.



5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it’s highly appropriate though, I’ll paste in the information.

Place JS at bottom

Remember — the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can’t continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

  1. <p>And now you know my favorite kinds of corn. </p>  
  2. <script type="text/javascript" src="path/to/file.js"></script>  
  3. <script type="text/javascript" src="path/to/anotherFile.js"></script>  
  4. </body>  
  5. </html>  

6. Declare Variables Outside of the For Statement

When executing lengthy “for” statements, don’t make the engine work any harder than it must. For example:

Bad

  1. for(var i = 0; i < someArray.length; i++) {  
  2.    var container = document.getElementById('container');  
  3.    container.innerHtml += 'my number: ' + i;  
  4.    console.log(i);  
  5. }  

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

Better

  1. var container = document.getElementById('container');  
  2. for(var i = 0, len = someArray.length; i < len;  i++) {  
  3.    container.innerHtml += 'my number: ' + i;  
  4.    console.log(i);  
  5. }  

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.


7. The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

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

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative. 
- James Padolsey, james.padolsey.com


8. Reduce Globals

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries." 
- Douglas Crockford

  1. var name = 'Jeffrey';  
  2. var lastName = 'Way';  
  3.   
  4. function doSomething() {...}  
  5.   
  6. console.log(name); // Jeffrey -- or window.name  

Better

  1. var DudeNameSpace = {  
  2.    name : 'Jeffrey',  
  3.    lastName : 'Way',  
  4.    doSomething : function() {...}  
  5. }  
  6. console.log(DudeNameSpace.name); // Jeffrey  

Notice how we've "reduced our footprint" to just the ridiculously named "DudeNameSpace" object.


9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

  1. // Cycle through array and echo out each name.   
  2. for(var i = 0, len = array.length; i < len; i++) {  
  3.    console.log(array[i]);  
  4. }  

10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!


11. Don't Pass a String to "SetInterval" or "SetTimeOut"

Consider the following code:

  1. setInterval(  
  2. "document.getElementById('container').innerHTML += 'My new number: ' + i", 3000  
  3. );  

Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

  1. setInterval(someFunction, 3000);  

12. Don't Use the "With" Statement

At first glance, "With" statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example...

  1. with (being.person.man.bodyparts) {  
  2.    arms = true;  
  3.    legs = true;  
  4. }  

-- instead of --

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

Unfortunately, after some testing, it was found that they "behave very badly when setting new members." Instead, you should use var.

  1. var o = being.person.man.bodyparts;  
  2. o.arms = true;  
  3. o.legs = true;  

13. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

  1. var o = new Object();  
  2. o.name = 'Jeffrey';  
  3. o.lastName = 'Way';  
  4. o.someFunction = function() {  
  5.    console.log(this.name);  
  6. }  

However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

  1. var o = {  
  2.    name: 'Jeffrey',  
  3.    lastName = 'Way',  
  4.    someFunction : function() {  
  5.       console.log(this.name);  
  6.    }  
  7. };  

Note that if you simply want to create an empty object, {} will do the trick.

"Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc." - dyn-web.com


14. Use [] Instead of New Array()

The same applies for creating a new array.

Okay

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

Better

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

"A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object." - Douglas Crockford


15. Long List of Variables? Omit the "Var" Keyword and Use Commas Instead

  1. var someItem = 'some string';  
  2. var anotherItem = 'another string';  
  3. var oneMoreItem = 'one more string';  

Better

  1. var someItem = 'some string',  
  2.     anotherItem = 'another string',  
  3.     oneMoreItem = 'one more string';  

...Should be rather self-explanatory. I doubt there's any real speed improvements here, but it cleans up your code a bit.


17. Always, Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

  1. var someItem = 'some string'  
  2. function doSomething() {  
  3.   return 'something'  
  4. }  

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

Better

  1. var someItem = 'some string';  
  2. function doSomething() {  
  3.   return 'something';  
  4. }  

18. "For in" Statements

When looping through items in an object, you might find that you'll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

  1. for(key in object) {  
  2.    if(object.hasOwnProperty(key) {  
  3.       ...then do something...  
  4.    }  
  5. }  

As referenced from JavaScript: The Good Parts, by Douglas Crockford.


19. Use Firebug's "Timer" Feature to Optimize Your Code

Need a quick and easy way to determine how long an operation takes? Use Firebug's "timer" feature to log the results.

  1. function TimeTracker(){  
  2.  console.time("MyTimer");  
  3.  for(x=5000; x > 0; x--){}  
  4.  console.timeEnd("MyTimer");  
  5. }  

20. Read, Read, Read...

While I'm a huge fan of web development blogs (like this one!), there really isn't a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

Read them...multiple times. I still do!


21. Self-Executing Functions

Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

  1. (function doSomething() {  
  2.    return {  
  3.       name: 'jeff',  
  4.       lastName: 'way'  
  5.    };  
  6. })();  

22. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding -- especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery's "each" method is great for looping, but using a native "for" statement will always be an ounce quicker.


23. Crockford's JSON.Parse

Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

Simply by importing the script, you'll gain access to a new JSON global object, which can then be used to parse your .json file.

  1. var response = JSON.parse(xhr.responseText);  
  2.   
  3. var container = document.getElementById('container');  
  4. for(var i = 0, len = response.length; i < len; i++) {  
  5.   container.innerHTML += '<li>' + response[i].name + ' : ' + response[i].email + '</li>';  
  6. }  

24. Remove "Language"

Years ago, it wasn't uncommon to find the "language" attribute within script tags.

  1. <script type="text/javascript" language="javascript">  
  2. ...  
  3. </script>  

However, this attribute has long since been deprecated; so leave it out.

机器学习规则:ML工程最佳实践----rules_of_ml section 1【翻译】

机器学习规则:ML工程最佳实践本文旨在指引具有机器学习基础知识的工程师等人,更好的从机器学习的实践中收益。介绍一些应用机器学习需要遵循的规则,类似于Google C++ 风格指南等流行的编程指南。如果...
  • wangyaninglm
  • wangyaninglm
  • 2017年05月20日 00:40
  • 933

机器学习法则:(谷歌)机器学习工程最佳实践(译)

本文来源:《Rules of Machine Learning:Best Practices for ML Engineering》作者:Martin Zinkevich google 研究科学家。...
  • Allenalex
  • Allenalex
  • 2017年05月07日 23:08
  • 1269

使用unslider.js图片轮播插件创建一个能轮播24节气的网页

使用unslider.js图片轮播插件创建一个能轮播24节气的网页 24节气图片来自花瓣网,背景图片来源于网络 unslider.js需要jquery的支持 资源地址github ...
  • QQ1360303452
  • QQ1360303452
  • 2015年10月26日 00:39
  • 998

Email Best Practices邮件发送策略最佳实践

Email Best Practices ReputationHostingIP Addresses and Sending VolumeDNSAuthenticationMailing List...
  • u013695144
  • u013695144
  • 2015年03月27日 13:46
  • 594

Android 6.0 开发者对系统权限的使用与练习(Permissions Best Practices)

Permissions Best Practices    在安装的过程中,用户很容易忽略权限请求。如果一个用户对应用感觉沮丧或者担心泄漏个人信息,那么这些用户就会不用他或者卸载它。如何规避这个问题...
  • zz20104534
  • zz20104534
  • 2016年02月22日 17:15
  • 1411

【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】

【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Say you have a...
  • DERRANTCM
  • DERRANTCM
  • 2015年08月14日 06:16
  • 6346

android studio小日常(持续更新)

这里会更新一些android  studio大家可能找不到的地方,也是比较常用的一些技巧。 1.我们在使用android studio编辑xml的时候,我们想让xml能自动选择合适的版本进行预览,我们...
  • BXHUHU10910
  • BXHUHU10910
  • 2016年05月21日 11:04
  • 586

U3D HTTP 最好用的插件BestHttp

简介我用的是1.6版,附百度云地址链接:http://pan.baidu.com/s/1dDzW4XN 密码:xz6aUnity用来和服务器通信可以用原生的WWW,但是WWW所提供的功能并不多,不能满...
  • Kaitiren
  • Kaitiren
  • 2015年09月12日 18:18
  • 10230

hdu 5451 Best Solver 快速矩阵乘法 Fibonacci数列的循环节

Best Solver Time Limit: 1500/1000 MS (Java/Others)    Memory Limit: 65535/102400 K (Java/Others) Tot...
  • firenet1
  • firenet1
  • 2015年09月22日 21:54
  • 1085

“Docker Practice”学习笔记

一本很不错的Docker入门书籍,github地址, 自己仔细看完了前14章, 提了一个pull request, 修改了3个issue! 关键字:docker, Union FS(AUFS), c...
  • wuzhimang
  • wuzhimang
  • 2017年06月18日 15:06
  • 526
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:24 JavaScript Best Practices for Beginners
举报原因:
原因补充:

(最多只允许输入30个字)