Five quick JavaScript tips

http://usabletype.com/

http://www.blueidea.com/

When we’re hiring JavaScript developers at Multimap we sometimes ask them to build a little application, or mash-up, with the Multimap API. It’s a pretty simple little task but it allows us to see how people approach building a web application.

This is a list of five things I often notice when looking at these little applications that could be improved. They may be obvious to some people, but certainly not to all. So, without more ado: five quick JavaScript tips to improve the quality of your code.

Use the submit event on forms
When attaching event handlers to forms, always use the submit event of the form and not the click event of the submit button.

If something is clickable, make sure it’s a link
Don’t attach click events to elements other than anchors. This is particularly important for users navigating the site with methods other than the mouse, where they may have difficulty getting focus on non-anchor elements.

Simple loop optimisation
There’s a very simple change you can make to a for loop to improve it’s performance.

for ( var i = 0; i < elements.length; ++i )
for ( var i = 0, j = elements.length; i < j; ++i )
In the second example the length of the elements array is stored in the j variable, so it’s not queried on every iteration of the loop.

Use anonymous functions for event handlers
Particularly with short functions like the below, it is far more readable to create an anonymous function than to reference another named function elsewhere. It also allows you to use closures of course.

anchor.onclick = function() {
map.goToPosition( home );
return false;
}
Use Array.join instead of concatenating strings
When working with long strings that need to be joined up, it is more readable and better for performance to place strings in an array and use the join method to return a string.

var text = 'There are' + elements.length + 'members in the elements array.';
var text = ['There are', elements.length, 'members in the elements array.'].join(' ');
Update

A number of people have mentioned to me that the Array.join technique for string concatenation is a bad one, particularly if you're only doing it with a small number of strings. Our benchmarks show it being faster for IE when you get to about 6/7 string concatenations, so it's been useful to us in some situations. But I'd agree with Stuart below that for the average situation it's not going to be worth it. However, I don't see using Array.join() for string concatenation as an abuse of JavaScript.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值