最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jsLint Expected { - Stack Overflow

programmeradmin2浏览0评论

Given the following

for(var i=0; i< data.cats.length; i++) list += buildCategories(data.cats[i]);

jsLint tells me

Expected '{' and instead saw 'list'.

Is there an actual disadvantage to using the shorter notation instead of wrapping it it curly braces?

Given the following

for(var i=0; i< data.cats.length; i++) list += buildCategories(data.cats[i]);

jsLint tells me

Expected '{' and instead saw 'list'.

Is there an actual disadvantage to using the shorter notation instead of wrapping it it curly braces?

Share Improve this question asked Mar 13, 2012 at 19:04 darryn.tendarryn.ten 6,9733 gold badges49 silver badges66 bronze badges 1
  • if you are sure you don't want that check, then simply change the hinting configuration by supplying "curly":false, – Kiran Shakya Commented Oct 24, 2016 at 1:26
Add a comment  | 

3 Answers 3

Reset to default 14

It is defensive programming - using curly brackets clearly defines which statements are intended to be associated with the for.

If you don't use curly brackets, at a later point someone might mistakenly add another statement underneath list += buildCategories... expecting it to get executed with the for loop as well.

"Is there an actual disadvantage to using the shorter notation..."

It may be the source of bugs if you're not careful about your coding, but omitting them provides cleaner code IMO, and if you adhere to consistent and well thought programming standards, omitting them won't be an issue.

For example, when I have nested if/else statements that are otherwise able to exclude the braces, I prefer to balance the elses over using braces.

if (condition)
    if (condition2)
        inner_if()
    else ;
else
    outer_if()

That code is still cleaner than this IMO...

if (condition) {
    if (condition2) {
        inner_if();
    }
} else {
    outer_if();
}

If someone things they can add another statement to an if or else, then that's an issue of understanding that needs to be fixed.

So really it's just a question of what standards are to be used. Taking advantage of curly braces is certainly one valid option, but we shouldn't be too dogmatic about it.


If you want a more configurable tool, you could consider jsHint.com instead.

JSLint checks for following good code style. Inserting curly braces is always good style because it is obvious where the code belongs to. And that it is shorter is not really an argument since most minifiers take care of that anyway.

发布评论

评论列表(0)

  1. 暂无评论