When passing the following code to jshint, it considers the linebreak in the if-condition to be bad, saying "Bad line breaking before '&&'."
if (1 == 1
&& true) {
console.log("hello world");
}
However, having the linebreak after '&&' is fine.
if (1 == 1 &&
true) {
console.log("hello world");
}
Why does jshint consider the first to be wrong and the latter to be right?
According to a discussion on GitHub:
This may cause problems like semi colon insertion and old javascript parsers breaking. Please check a large range of browsers.
This check can be disabled with laxbreak:true.
The laxbreak option is on its way to deprecation, but I'm not sure if the default jshint behavior will change.
The creator of JSHint probably doesn't like this kind of wrapping and prefers the && in the first line which seems to be much more common:
The primary reasoning behind this convention is that the operator makes it clear that the line is a continuation of the preceding line. With the operator before the line break, this is much harder to spot.
Actually there's an issue about exactly what you are asking about on Github: https://github.com/jshint/jshint/issues/557
Related
I have the following code amd it gives me compilation error:
for(var i in test){
(this.watcherFailureCount> 10) && break
}
However the following works:
if(this.watcherFailureCount> 10)
{
break
}
Am I missing anything here? why the first one is not working for me?
The && tries to evaluate your expression and cast its return value to boolean. The break you use is a keyword that controls the loop and should not be used in expressions.
Some languages allow that but it just seems that js doesn’t. And to be fair it is ok not to because is missleading. Imagine conditions like: a && b && break && c && d = a.
There is no real benefit in the first option unless you codegolf or something, and if you codegolf you chosed the wrong language :).
Dont fully understand what youre trying to achieve here however impretty sure the first code snippet is incorrect syntax.
If you want that as an inline if statement try:
if(this.watcherFailureCount>10)break;
However ensure if you are using break that it is inside of some form of code loop like a while or a for loop. And using && with break is invalid as break cannot be a true or false statement so it cant be used like that.
I'm linting my JavaScript with JSHint, and have this option enabled
"asi": true,
"white": true
to avoid semicolons in my code.
But I have to begin my new line with a bracket, so I have to put a semicolon before the opening of that one
;(function () {
})
JSHint give me two errors:
Missing space after ';'
If I put a space after ';' I get: Expected '(' to have a different identation
I noticed that in this way JSHint is happy
;
(function () {
})
but I think is not a good solution.
Is there a way to solve this problem, without turning off JSHint or the white option?
The legacy white: true option in JSHint is used to enforce the coding style promoted by Douglas Crockford in his original JSLint tool. Semicolon-less JavaScript code will not fit his coding style. If you don't want to be restricted to his style guidelines then don't use white: true.
This list of JSHint options doesn't show any parameters to customize the coding style they enforce.
To prove that there isn't an answer to this, I went and found the relevant check in the JSHint source:
function nonadjacent(left, right) {
if (option.white) {
left = left || token;
right = right || nexttoken;
if (left.line === right.line && left.character === right.from) {
left.from += (left.character - left.from);
warning("Missing space after '{a}'.",
left, left.value);
}
}
}
The only configuration option checked is option.white, so unfortunately there isn't any way to achieve your desired behavior. If you really wanted a tool that would do exactly what you want, you could easily fork JSHint, add another option, and check it in the nonadjacent function.
Why JSLint report in code:
function cos(a) {
var b = 0;
if (a) {
b = 1;
}
else {
b = 2;
}
return b;
}
error:
Problem at line 6 character 5: Expected exactly one space between '}' and 'else'.
This error can be turned off by disabling Tolerate messy white space option of JSLint.
Or in other words -- why syntax:
} else { is better then
...
}
else {
...
Google also uses syntax with } else { form.
But I don't understand why. Google mentioned ''implicit semicolon insertion'', but in context of opening {, not closing one.
Can Javascript insert semicolon after closing } of if block even if next token is else instruction?
Sorry that my question is a bit chaotic -- I tried to think loud.
JSLint is based on Crockford's preferences (which I share in this case).
It's a matter of opinion which is "better".
(Although clearly his opinion is right ;)
It's not a matter of style. It's how ECMAScript works.
For better or for worse, it will automatically insert semicolons at the end of statements where it feels necessary.
JavaScript would interpret this:
function someFunc {
return
{
something: 'My Value'
};
}
As this:
function someFunc {
return;
{
something: 'My Value'
};
}
Which is certainly what you don't want.
If you always put the bracket on the same line as the if and if else statement, you won't run into a problem like this.
As with any coding language, the coding style chosen should be the one that minimizes potential risk the most.
Mozilla Developer Network also promotes same line bracketing: https://developer.mozilla.org/en-US/docs/User:GavinSharp_JS_Style_Guidelines#Brackets
JSLint is being very picky here, just enforcing a style that you might not share.
Try JSHint instead:
The project originally started as an effort to make a more configurable version of JSLint—the one that doesn't enforce one particular coding style on its users [...]
JSLint is just being picky here. The guy who wrote it also baked in many stylistic suggestions in order to keep his own code more consistent.
As for semicolon insertion, you shouldn't need to worry here. Inserting a semicolon before the else clause would lead to a syntax error and automatic semicolon insertion only occurs in situations where the resulting code would still be syntactically valid.
If you want to read more on semicolon insertion, I recommend this nice reference
Basically if you insert semicolons everywhere you only need be careful about putting the argument to "return" or "throw" (or the label for "break" and "continue") on the same line.
And when you accidentally forget a semicolon, the only common cases that are likely to bite you are if you start the next line with an array literal (it might parsed as the subscript operator) or a parenthsised expression (it might be parsed as a function call)
Conclusion
Should you omit optional semicolons or not? The answer is a matter of
personal preference, but should be made on the basis of informed
choice rather than nebulous fears of unknown syntactical traps or
nonexistent browser bugs. If you remember the rules given here, you
are equipped to make your own choices, and to read any JavaScript
easily.
If you choose to omit semicolons where possible, my advice is to
insert them immediately before the opening parenthesis or square
bracket in any statement that begins with one of those tokens, or any
which begins with one of the arithmetic operator tokens "/", "+", or
"-" if you should happen to write such a statement.
Whether you omit semicolons or not, you must remember the restricted
productions (return, break, continue, throw, and the postfix increment
and decrement operators), and you should feel free to use linebreaks
everywhere else to improve the readability of your code.
By the way, I personally think that the } else { version is prettier. Stop insisting in your evil ways and joins us on the light side of the force :P
I have just finished reading a book titled Mastering JavaScript High Performance. I speak under correction here, but from what I can gather is that "white space" does in fact matter.
It has to do with the way the interpreter fetches the next function. By keeping white space to a minimum (i.e.) using a minifier when your code is ready for deployment, you actually speed up the process.
If the interpreter has to search through the white space to find the next statement this takes time. Perhaps you want to test this with a piece of code that runs a loop say 10,000 times with white space in it and then the same code minified.
The statement to put before the start of the loop would be console.time and finally console.timeEnd at the end of the loop. This will then tell you how many milliseconds the loop took to compute.
The JSLint error/warning is suggesting to alter code to
// naming convention winner? it's subjective
} else if{
b = 2;
}
from:
}
else if{
b = 2;
}
It prevents insert semicolons; considered more standard & conventional.
most people could agree a tab between the
}tabelse if{
is not the most popular method. Interesting how the opening bracket { is placed (space or not) obviously both ar subjected
This is my JavaScript (much stripped down):
function addContent() {
var content = [];
content.append(
makeVal({
value : 1
})
); // Generates lint message
}
Running a lint program over this, I get the message
unexpected end of line; it is ambiguous whether these lines are part of the same statement
on line 7. If I concatenate lines 6 and 7 the message goes away.
Can anyone explain where this ambiguity is? It seems to me that the parenthesis on line 7 is unambiguously closing the call to append().
It looks that way to me, too. Sounds like a bug in the lint program you're using.
You can understand why it would wonder, because the call to makeVal fits the profile of code that's relying on semicolon insertion — unless you look correctly at the wider context and realize it's within argument list for the append call. Seems to me the lint program is not actually parsing the language, just looking for patterns, which is going to mean it's going to have both false positives and false negatives.
I have a minified/packed javascript file which is causing problems. The issue is that the non-packed input file has some missing semicolons somewhere which aren't a problem when there's line breaks, but when the file is packed, the line breaks are removed and that causes a parser error. For example:
//input
var x = function() {
doSomething();
} // note: no semicolon
var y = 'y';
//----
// output
var x=function(){doSomething();}var y='y';
// error here: ^
The strange thing is that when I do a replace on the output file to replace all semicolons with a semicolon and a new line, the file works! This is making it ludicrously hard to find the error, since AFAIK, I can't think of any situation where a line break after a semicolon should change anything. Any ideas about why doing this replace would make it work?
Uh... Have you tried JSLint?
When there's a line break, there's an implied semi-colon.
Use jslint to check your code. If you do this and get it passing with regards to semicolons, it should pack correctly.
In JavaScript, semicolons are implicitly added at newlines. This introduces situations that can be ambiguous. This blog post: http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/ describes the problem succinctly and gives an example.
JSlint is a good solution. Also, some code editors will find these kinds of errors for you. If I recall correctly, NetBeans catches these in realtime, as you type. I believe Komodo and Aptana do as well.