24个JavaScript初学者最佳实践
- 这里面说到的一个就是使用循环新建一个字符串时,用到了join(),这个比较高效,常常会随着push();
- 绑定某个动作时,可以把要执行的绑定内容定义为一个函数,然后再执行。这样做的好处有很多。第一是可以多次执行,第二是方便调试,第三是方便重构。
As a follow-up to “30 HTML and CSS Best Practices”, this week, we’ll review JavaScript! Once you’ve reviewed the list, be sure to let us know what little tips you’ve come across!
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:
if(someVariableExists)
x = false
However, consider this:
if(someVariableExists)
x = false
anotherFunctionCall();
One might think that the code above would be equivalent to:
if(someVariableExists) {
x = false;
anotherFunctionCall();
}
Unfortunately, he’d be wrong. In reality, it means:
if(someVariableExists) {
x = false;
}
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.
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.

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
<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>
</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
for(var i = 0; i < someArray.length; i++) {
var container = document.getElementById('container');
container.innerHtml += 'my number: ' + i;
console.log(i);
}
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
var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len; i++) {
container.innerHtml += 'my number: ' + i;
console.log(i);
}
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.
var arr = ['item 1', 'item 2', 'item 3', ...];
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
var name = 'Jeffrey';
var lastName = 'Way'; function doSomething() {...} console.log(name); // Jeffrey -- or window.name
Better
var DudeNameSpace = {
name : 'Jeffrey',
lastName : 'Way',
doSomething : function() {...}
}
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.
// Cycle through array and echo out each name.
for(var i = 0, len = array.length; i < len; i++) {
console.log(array[i]);
}
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 toprogressively enhance your layout!
11. Don’t Pass a String to “SetInterval” or “SetTimeOut”
Consider the following code:
setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
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.
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…
with (being.person.man.bodyparts) {
arms = true;
legs = true;
}
– instead of –
being.person.man.bodyparts.arms = true;
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.
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. Perhaps the more traditional method is to use the “new” constructor, like so:
var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
console.log(this.name);
}
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
var o = {
name: 'Jeffrey',
lastName = 'Way',
someFunction : function() {
console.log(this.name);
}
};
Note that if you simply want to create an empty object, {} will do the trick.
var o = {};
“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
var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';
Better
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
var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';
Better
var someItem = 'some string',
anotherItem = 'another string',
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.
var someItem = 'some string'
function doSomething() {
return 'something'
}
Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.
Better
var someItem = 'some string';
function doSomething() {
return 'something';
}
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
for(key in object) {
if(object.hasOwnProperty(key) {
...then do something...
}
}
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.
function TimeTracker(){
console.time("MyTimer");
for(x=5000; x > 0; x--){}
console.timeEnd("MyTimer");
}
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.
(function doSomething() {
return {
name: 'jeff',
lastName: 'way'
};
})();
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.
var response = JSON.parse(xhr.responseText); var container = document.getElementById('container');
for(var i = 0, len = response.length; i < len; i++) {
container.innerHTML += '
- ‘ + response[i].name + ‘ : ‘ + response[i].email + ‘
‘; }
24. Remove “Language”
Years ago, it wasn’t uncommon to find the “language” attribute within script tags.
<script type="text/javascript" language="javascript">
...
</script>
However, this attribute has long since been deprecated; so leave it out.
That’s All, Folks
So there you have it; twenty-four essential tips for beginning JavaScripters. Let me know your quick tips! Thanks for reading. What subject should the third part in this series cover?
24个JavaScript初学者最佳实践的更多相关文章
- 24. javacript高级程序设计-最佳实践
1. 最佳实践 l 来自其他语言的代码约定可以用于决定何时进行注释,以及如何进行缩进,不过JavaScript需要针对其松散类型的性质创造一些特殊的约定 l javascript应该定义行为,html ...
- 给JavaScript初学者的24条最佳实践
.fluid-width-video-wrapper { width: 100%; position: relative; padding: 0 } .fluid-width-video-wrapp ...
- 给JavaScript初学者的24条最佳实践(share)
不错的文章,留个备份 原文链接: net.tutsplus 翻译: 伯乐在线- yanhaijing译文链接: http://blog.jobbole.com/53199/ 作为“30 HTML和 ...
- 给JavaScript初学者的24条最佳实践(转:http://www.cnblogs.com/yanhaijing/p/3465237.html)
作为“30 HTML和CSS最佳实践”的后续,本周,我们将回顾JavaScript的知识 !如果你看完了下面的内容,请务必让我们知道你掌握的小技巧! 1.使用 === 代替 == JavaScript ...
- 转载----给JavaScript初学者的24条最佳实践
给JavaScript初学者的24条最佳实践 1.使用 === 代替 == JavaScript 使用2种不同的等值运算符:===|!== 和 ==|!=,在比较操作中使用前者是最佳实践. “如果 ...
- JavaScript初学者福利!必须收藏的24条小技巧
JavaScript初学者福利!必须收藏的24条小技巧 前端小编 发布于 2013-12-15 22:52 查看数: 2343 评论数: 6 帖子模式 这篇文章将回顾JavaScript的知识 !如果 ...
- 给JavaScript24条最佳实践
作为“30 HTML和CSS最佳实践”的后续,这篇文章将回顾JavaScript的知识 !如果你看完了下面的内容,请务必让我们知道你掌握的小技巧! 1.使用 === 代替 == JavaScript ...
- 2 JavaScript应用开发实践指南
JavaScript 语言在浏览器中的运用 HTTP请求,加载HTML后根据内容加载CSS等,大部分浏览器默认2个下载链接. HTML元素要尽可能简洁,不需要将Table元素变成多个div, css代 ...
- JavaScript 初学者应知的 24 条最佳实践
原文:24 JavaScript Best Practices for Beginners (注:阅读原文的时候没有注意发布日期,觉得不错就翻译了,翻译到 JSON.parse 那一节觉得有点不对路才 ...
随机推荐
- IOS开发——Protocol使用协议
protocol ['prəutəkɔl] (样例:http://blog.sina.com.cn/s/blog_6aafe9c90100yozz.html ) 一.说明 两个类进行通讯,用协议就比 ...
- Base64中文不能加密问题
最近用到了Base64.js来对url参数进行加密,字母和数字都可以很好地加密/解密. 但测试中文时发现不能进行转换,貌似Base64.js不支持中文字符. 联想到encodeURI()对url的编码 ...
- SQL Server表分区详解
原文:SQL Server表分区详解 什么是表分区 一般情况下,我们建立数据库表时,表数据都存放在一个文件里. 但是如果是分区表的话,表数据就会按照你指定的规则分放到不同的文件里,把一个大的数据文件拆 ...
- Ajax跨域请求数据实例(JSOPN方式)
今天在做取消申请的时候遇到了一个跨域ajax提交的问题. 情景是: 系统A是asp.net的站点,其中包括一个取消申请的接口(get方式通过参数提交到系统的某一个页面,然后返回提交成功或失败) 系统B ...
- 从头学起android<android基本的绘图.四十六.>
在一般的图形渲染用户通常只需要重写onDraw()该方法可以是.但是假设,才能真正完成绘图操作.此外,我们需要掌握的四大核心经营类: android.graphics.Bitmap:主要表示的是一个图 ...
- Android FM学习中的模块 FM启动过程
最近的研究FM模,FM是一家值我正在学习模块.什么可以从上层中可以看出. 上层是FM按钮的操作和界面显示,因此调用到FM来实现广播收听的功能. 看看Fm启动流程:例如以下图: 先进入FMRadio.j ...
- Linux:闪光的宝石,智慧(下一个)
2005年4月7日.Linus Torvalds公布了一款新型通用工具软件包,叫做"Git"(the Git source code management system).&quo ...
- WebService返回DataTable问题
今天做项目时,想在WebService中返回DataTable,在单位没成功,看网上有人说datable在.net1.1中是没有序列化的,不能直接在webservice中返回,可以返回dataset. ...
- Web文件(图片)上传方法
在开放Web应用程序的时候经常会遇到图片或者是文件上传的模块,这里就是该模块的实现的后台方法 上传图片方法 /// <summary> /// 功能:上传图片方法 /// </sum ...
- 我们的空间是它圆——基于Poicare对宇宙的模型
一般 状态 在人类文明的开始,并探讨了空间和时间的混乱从来没有停止过.马跑得更快.鱼下潜深.鸟振翅高飞,但是,人类并没有很深的不满潜飞不高.为什么?其原因是,马跑得更快,但它不会不知道他们为什么会跑得 ...