Put semicolons in asi mode before brackets - javascript

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.

Related

Authorization is better written in dot notation [duplicate]

Is there an option to and/or how do I suppress errors like the following?
175,14:['tracker'] is better written in dot notation.
If it's a feature and not a bug, place this at the top of your file.
/*jshint sub:true*/
If it's a bug, you should refactor your code
foo['tracker'] = bar // from this...
foo.tracker = bar; // to this!
Good post on the reasons here: https://stackoverflow.com/a/2001410/94668
As suggested by: #ThorSummoner you can use below in your .jshintrc file
"sub": true
In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax. The identifier of this warning is W069.
This means you can tell JSHint to not issue this warning with the /*jshint -W069 */ directive.
You can even wrap several lines of code and then reenable the warning as the example below (with a note to future you why it was a good idea):
/*jshint -W069 */
/*Disable Warning Justification:
Using bracket notation so Google Closure Compiler
ADVANCED_OPTIMIZATIONS will keep the original property names. */
obj['prop1'] ='foo';
obj['prop2'] ='bar';
/*jshint +W069 */
I assume you are asking about Dreamweaver or another editor.
Dreamweaver
You may go to Edit -> Preferences -> Linting
Select JS in the dropdown and hit Edit & Apply changes
Find
"sub": false,
and change that to true. Save the file and that notice will disappear.
If you have OTHER Linting things you wish to edit, you can find a helpful list of them all at https://jshint.com/docs/options/

Why does jshint complain about linebreak within expression?

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

How to suppress "{variable} is better written in dot notation."

Is there an option to and/or how do I suppress errors like the following?
175,14:['tracker'] is better written in dot notation.
If it's a feature and not a bug, place this at the top of your file.
/*jshint sub:true*/
If it's a bug, you should refactor your code
foo['tracker'] = bar // from this...
foo.tracker = bar; // to this!
Good post on the reasons here: https://stackoverflow.com/a/2001410/94668
As suggested by: #ThorSummoner you can use below in your .jshintrc file
"sub": true
In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax. The identifier of this warning is W069.
This means you can tell JSHint to not issue this warning with the /*jshint -W069 */ directive.
You can even wrap several lines of code and then reenable the warning as the example below (with a note to future you why it was a good idea):
/*jshint -W069 */
/*Disable Warning Justification:
Using bracket notation so Google Closure Compiler
ADVANCED_OPTIMIZATIONS will keep the original property names. */
obj['prop1'] ='foo';
obj['prop2'] ='bar';
/*jshint +W069 */
I assume you are asking about Dreamweaver or another editor.
Dreamweaver
You may go to Edit -> Preferences -> Linting
Select JS in the dropdown and hit Edit & Apply changes
Find
"sub": false,
and change that to true. Save the file and that notice will disappear.
If you have OTHER Linting things you wish to edit, you can find a helpful list of them all at https://jshint.com/docs/options/

JSLint, else and Expected exactly one space between '}' and 'else' error

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

Why no semicolon at the end of js expression in javascriptmvc app?

I am starting to learn javascriptmvc, and in code samples, I see code without semicolons at the end of expressions. Does this count on automatic semicolon insertion or am I missing something? Code example below:
$.Controller("Contacts.Controller", {
init: function(){
this.params = new Mxui.Data();
$("#category .list_wrapper").mxui_data_list({
model : Contacts.Models.Category,
show : "//contacts/views/categoryList",
create: "//contacts/views/categoryCreate"
}) // <------ NO SEMICOLON
$("#location .list_wrapper").mxui_data_list({
model : Contacts.Models.Location,
show : "//contacts/views/categoryList",
create: "//contacts/views/categoryCreate"
}) // <------ NO SEMICOLON
$("#company .list_wrapper").mxui_data_list({
model : Contacts.Models.Company,
show : "//contacts/views/companyList",
create: "//contacts/views/companyCreate"
}) // <------ NO SEMICOLON
// etc...
}
}) // <------ NO SEMICOLON
Javascript can be forgiving about the lack of a semicolon in ways that other languages are not. However a semicolon is recommended where you've pointed them out.
If you run the code you've given through JSLint, it throws up a whole stack of warnings, including complaining about those missing semicolons.
JSLint is a tool for telling you about things in your code which may not be syntax errors but which could cause problems. It generally throws up a lot of errors, even for relatively well written code, but it is good for picking up things which you should fix.
I would say that those code samples are poorly written because of the missing semi-colons.
Semicolons are only mandatory in inline event handlers.
MOST anywhere else, a linefeed is enough. Here is an example of where it is not enough:
Why is a semicolon required at end of line?
And as pointed out, do not leave out semicolons if you want to minify your scripts.
A lot of semicolons are optional in javascript, though recommended to avoid confusion
https://mislav.net/2010/05/semicolons/

Categories

Resources