A programming convention that is frequently carried into JavaScript from other languages (often by C++ and C developers) is the scoping of functionality within isolated blocks of code (i.e. between parentheses).
Take the following:
int y = 2;
{
int x = 3+y;
DoSomethingWith(x);
}
But JavaScript is less fussy about scoping, so the following will execute probably execute without complaint:
var y = 2;
{
var x = 3;
}
alert(x+y); //alerts '5'
The use of the block here, therefore, is just extra noise. Its more characters to be written, read and transmitted. In addition to this, in some cases its contrary to the language specification. Consider the use of the ‘case’ statement:
var x = 0;
switch(x){
case 0:{
var y = 1;
alert(y);
}
}
Here we have added some parentheses to the ‘case’ block of code. In C, C++, this sort of convention is necessary. In JavaScript, it is not, so the following will work happily:
var x = 0;
switch(x){
case 0:
var y = 1;
alert(y);
}
The first statement is contrary to the language specification. (Refer to the official EC5 Specification and the Mozilla JavaScript reference for more information). This reason alone is justification enough for JSLint to throw the error ‘Expected to see a statement and instead saw a block’, even before considering the extra noise the blocks create.
There is another potential argument against the use of (bogus) scoping blocks in this way. JavaScript also uses parentheses for objects and object literal declarations:
var y = {
x:3,
f:2
};
So, avoiding the specification of bogus scoped blocks will also make our code easier to read and subject to less confusion.
A Guide To JSLint Messages
This article is one of a series on the error and warning messages produced by JSLint.
[...] or ‘,’ or ‘[' preceding a regular expression literal, and instead saw '{a}'. Expected to see a statement and instead saw a block. Extra comma. Function statements are not invocable. Wrap the function expression in parens. get/set [...]